﻿#NoEnv
#SingleInstance Force
SetBatchLines, -1
Process, Priority,, High
SetWorkingDir %A_ScriptDir%
SetTitleMatchMode,RegEx
OnMessage(0x201, "MoveActiveWindows")
OnMessage(0x200, "WM_MOUSEMOVE")
#Include lib\Class_Yaml.ahk
#Include lib\Class_Scinitlla.ahk
;=================================================================================================
if (A_AhkVersion<1.1.33){
	MsgBox,262160,Error,ahk主程序版本过低，要求1.1.33+,10
	ExitApp
}
;================================管理员身份检查与处理================================================
If !A_IsAdmin {
	Try
	{
		If A_IsCompiled {
			Run *RunAs "%A_ScriptFullPath%" /restart
			ExitApp
		}else{
			Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
		}
	}Catch e{
		MsgBox, 262160,Error,% e.Extra?e.Extra:"`n以管理员身份运行失败！",15
		ExitApp
	}
}
;;=====================================================================================================
;;=====================================================================================================
if !FileExist(A_AppData "\RimeToolData\Weasel")
	FileCreateDir,%A_AppData%\RimeToolData\Weasel
if !FileExist(A_AppData "\RimeToolData\x64")
	FileCreateDir,%A_AppData%\RimeToolData\x64
if !FileExist(A_AppData "\RimeToolData\x86")
	FileCreateDir,%A_AppData%\RimeToolData\x86
FileInstall, dll\SciLexer64.dll, %A_AppData%\RimeToolData\x64\SciLexer.dll , 1
FileInstall, dll\SciLexer32.dll, %A_AppData%\RimeToolData\x86\SciLexer.dll , 1
Default_Config:={IsCapsClear:1,IsTip:1,filter_extend:0}

Try {
	ConfigObject:=Json_FileToObj(A_AppData "\RimeToolData\Weasel\Weasel.Json")
	ConfigObject:=IsObject(ConfigObject)?ConfigObject:{}
}Catch{
	ConfigObject:={}
}

for Section,element In Default_Config
{
	if (ConfigObject[Section]="")
		%Section%:=ConfigObject[Section]:=element
	Else
		%Section%:=ConfigObject[Section]
}
SciLexer := A_AppData "\RimeToolData\" (A_PtrSize == 8 ?"x64":"x86") "\SciLexer.dll"
sciIsload:=LoadSciLexer(SciLexer)?1:0,Select_Color_Type:=1

Try {
	Json_ObjToFile(ConfigObject, A_AppData "\RimeToolData\Weasel\Weasel.Json", "utf-8")
}
;;========================================================================================
Hotkey,$^MButton,SetWinTop,On
;;=====================================================================================================
;;=====================================================================================================
if (A_Is64bitOS&&A_PtrSize>4){
	SetRegView, 64
}
if !A_IsCompiled
	Menu, TRAY,Icon,shell32.dll,131

RegRead, WeaselRoot, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, WeaselRoot
RegRead, InstallDir, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, InstallDir
RegRead, ServerExecutable, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, ServerExecutable
RegRead, RimeUserDir, HKEY_CURRENT_USER\Software\Rime\Weasel, RimeUserDir
Global RimeUserDir:=RimeUserDir?RimeUserDir:FileExist(A_AppData "\Rime\*.yaml")?A_AppData "\Rime":""
Global ServerExecutable:=ServerExecutable?RegExReplace(Trim(ServerExecutable,""""),".+\\"):"WeaselServer.exe"
Global TaskName:="小狼毫助手",StartTime:=SubStr(A_Now,1,12),ToolVersion:=2.70
if (RimeUserDir&&!WeaselRoot){
	Process,Exist,%ServerExecutable%
	if ErrorLevel
		Global WeaselRoot:=RegExReplace(GetProcessFullPath( ErrorLevel ),"\\[^\\]+$")
}

;=================================================================================================
Process,Exist,%ServerExecutable%
if !ErrorLevel {
	MatchWeaselItems.ToggleRunWeasel()
}
;================================托盘菜单==========================================================
Menu, TRAY, NoStandard
Menu, TRAY, DeleteAll
Menu, Tray, UseErrorLevel
Menu, TRAY,Add, 关于,OnAbout
Menu, TRAY,Add, 资源库,OnHelp
Menu, TRAY,Add,

Menu, Main,Add, 配色管理,options_color_scheme
Menu, Main,Add,
Menu, Main,Add, 状态管理,OnAppOptions
Menu, Main,Add,
Menu, Main,Add, 自启管理,OnAutoTask
Menu, Main,Add,
Menu, Main,Add, 用户词,GetUserDict
Menu, TRAY,Add, 自定义,:Main
Menu, TRAY,Add, 开机自启,AutoRunTool
Menu, Tray, Icon, 开机自启,shell32.dll,234
;自启项有效性检测并自动校正
if objCount(TaskActionExecPaths:=GetTaskActionExecPaths(TaskName)){
	if A_IsCompiled {
		if (TaskActionExecPaths[1,1]=A_ScriptFullPath){
			Menu, TRAY,Check, 开机自启
		}Else{
			if DisableAutorun(TaskName){
				if (EnableAutoRun(TaskName,"小狼毫辅助工具",(A_IsCompiled?A_ScriptFullPath:A_AhkPath),!A_IsCompiled?A_ScriptFullPath:"")=TaskName){
					Menu, TRAY,Check, 开机自启
				}
			}
		}
	}else{
		if (TaskActionExecPaths[1,1]=A_AhkPath&&TaskActionExecPaths[1,2]=A_ScriptFullPath){
			Menu, TRAY,Check, 开机自启
		}Else{
			if DisableAutorun(TaskName){
				if (EnableAutoRun(TaskName,"小狼毫辅助工具",(A_IsCompiled?A_ScriptFullPath:A_AhkPath),!A_IsCompiled?A_ScriptFullPath:"")=TaskName){
					Menu, TRAY,Check, 开机自启
				}
			}
		}
	}
}
Menu, TRAY,Add, 设置窗口,OnSetting
Menu, TRAY,Disable, 自定义
Menu, TRAY,Disable, 设置窗口
Menu, TRAY,Add,
Menu, TRAY,Add, 算法服务,ToggleRunWeasel
Menu, Tray, Icon, 算法服务,shell32.dll,234
Process, Exist , %ServerExecutable%
if ErrorLevel
	Menu, TRAY,Check, 算法服务
Else
	Menu, Tray, Icon, 算法服务,shell32.dll,234
Menu, TRAY,Add, 用户目录,GotoRimeUserDir
Menu, TRAY,Add, 程序目录,GotoWeaselRootDir
Menu, TRAY,Add, 重新部署,ReloadWeasel
Menu, TRAY,Add,
Menu, TRAY,Add, 重启程序,OnReload
Menu, TRAY,Color,ffffff
Menu, TRAY,Default,用户目录
Menu, TRAY,Add, 退出程序,OnExits
Gosub TrayMenuTip

Tray_Refresh()
;;================================监控消息回调ShellIMEMessage监控窗口变化================================
Gui,+LastFound
DllCall( "RegisterShellHookWindow", UInt,WinExist() )
OnMessage( DllCall( "RegisterWindowMessage", Str,"SHELLHOOK" ), "ShellIMEMessage")
;=================================================================================================
;================================重复进程检查与处理================================================
If A_IsCompiled {
	thisPID := DllCall("GetCurrentProcessId")
	if objCount(Processlist:=GetProcessNameList(A_ScriptName))>1
	{
		loop,% objCount(Processlist)
		{
			if (thisPID<>Processlist[A_Index,2]){
				process,Close,% Processlist[A_Index,2]
			}
		}
	}
}Else{
	DetectHiddenWindows, On
	thisPID := DllCall("GetCurrentProcessId")
	WinGet, List, List,%A_ScriptName% ahk_class AutoHotkey
	Loop % List
	{ 
		WinGet, PID, PID, % "ahk_id " List%A_Index%
		If (PID != thisPID){
			Process, Close, %PID%
		}
	}
	DetectHiddenWindows, Off
}
TrayIconInfo:=TrayIcon_GetInfo(A_IsCompiled?A_ScriptName:RegExReplace(A_AhkPath,".+\\"))
;;=======================================================================================
;;检查开机自启后丢失托盘图标并处理
if (!A_IconHidden) {
	if (A_IsCompiled&&!objcount(TrayIconInfo)){
		OnReload()
	}else if (!A_IsCompiled&&!objcount(TrayIconInfo)){
		OnReload()
	}else if (!A_IsCompiled&&objcount(TrayIconInfo)){
		IsNoHide:=0
		for key,value In TrayIconInfo
		{
			if (value.pid=DllCall("GetCurrentProcessId"))
				IsNoHide++
		}
		if !IsNoHide
			OnReload()
	}
}
;;================================程序图标如果隐藏托盘则提醒=================================
if objcount(TrayIconInfo){
	for key,value In TrayIconInfo
	{
		if (InStr(TrayIconInfo[key,"Tray"],"NotifyIconOverflowWindow")&&TrayIconInfo[key,"pid"]=DllCall("GetCurrentProcessId")){
			if !A_IconHidden
				Traytip,小狼毫助手,请把程序图标从托盘区移至`n任务栏以方便更好的操作！,,1
			Else
				MsgBox, 262144, 小狼毫助手,请把程序图标从托盘区移至`n任务栏以方便更好的操作！,10
		}
	}
}
TrayRefresh()
;;=====================================================================================================
symbolsNameArr:={},symbolsNameList:=""
symbolsName=
(
/dn	电脑符号
/fh	符号
/xq	国际象棋
/mj	麻将
/sz	色子
/pk	扑克
/bq	表情
/tq	天气
/yy	音乐
/bg	八卦
/bgm	八卦名
/lssg	六十四卦
/lssgm	六十四卦名
/txj	太玄经
/tt	天体
/xz	星座
/xzm	星座名
/seg	十二宫
/xh	星号
/fk	方块
/jh	几何
/jt	箭头
/sx	数学符号
/szq	数字圈
/szh	数字弧
/szd	数字点
/zmq	字母圈
/zmh	字母弧
/0	数字0
/1	数字1
/2	数字2
/3	数字3
/4	数字4
/5	数字5
/6	数字6
/7	数字7
/8	数字8
/9	数字9
/10	数字10
/fs	分数
/szm	苏州码
/lm	罗马数字小写
/lmd	罗马数字大写
/sb	上标
/xb	下标
/yf	月份
/rq	日期
/yr	曜日
/sj	时间
/tg	天干
/dz	地支
/gz	干支
/jq	节气
/dw	单位
/hb	货币
/jg	结构
/pp	偏旁
/kx	康熙部首
/bh	笔画
/bd	中文标点
/bdz	竖排标点
/py	拼音小写
/pyd	拼音大写
/zy	注音符号
/sd	声调
/hzq	汉字圈
/hzh	汉字弧
/iro	いろは順
/jm	假名
/pjm	片假名
/jmk	假名k
/jmg	假名g
/jms	假名s
/jmz	假名z
/jmt	假名t
/jmd	假名d
/jmn	假名n
/jmh	假名h
/jmb	假名b
/jmp	假名p
/jmm	假名m
/jmy	假名y
/jmr	假名r
/jmw	假名w
/jma	假名a
/jmi	假名i
/jmu	假名u
/jme	假名e
/jmo	假名o
/jmq	假名圈
/jmbj	假名半角
/hw	韩文
/hwq	韩文圈
/hwh	韩文弧
/lx	两性
/xl	希腊小写
/xld	希腊大写
/ey	俄语小写
/eyd	俄语大写
)
Loop,Parse,symbolsName,`n,`r
{
	if Trim(A_LoopField){
		tarr:=strSplit(A_LoopField,"`t")
	}
	symbolsNameArr[tarr[1]]:=tarr[2]
}

Try {
	GetSymbolsNameList(yaml(FileExist(RimeToolData "\symbols.yaml")?RimeToolData "\symbols.yaml":FileExist(WeaselRoot "\data\symbols.yaml")?WeaselRoot "\data\symbols.yaml":"")["punctuator","symbols"])
}

load_complete:=1
Menu, TRAY,Enable, 自定义
Menu, TRAY,Enable, 设置窗口

if Versions:=CheckVersion() {
	TrayTip,更新提示,小狼毫助手发现新版本，请右击托盘菜单 -「关于」更新！,,1
}

EmptyMem()
;;====================================================================================================
#if GetKeyState("CapsLock", "T")&&GetKeyState("Shift", "P")
	$Shift::
		SetCapsLockState , Off
		SendInput,{Shift Down}{Shift UP}
	Return
#if

#if GetKeyState("CapsLock", "P")&&WinExist("ahk_class ATL:*")&&!WinExist("ahk_exe " ServerExecutable)&&IsCapsClear||GetKeyState("CapsLock", "P")&&WinExist("ahk_class MSCTFIME*")&&!WinExist("ahk_exe " ServerExecutable)&&IsCapsClear
	$Capslock::
		SetCapsLockState , Off
		SendInput,{Esc Down}{Esc UP}
	Return
#if

#if WinExist("ahk_class ATL:*")&&!WinExist("ahk_exe " ServerExecutable)&&symbolsNameList&&IsTip
	$/::
		Rbtt:=btt(symbolsNameList,A_ScreenWidth-(btt_width?btt_width:0)-10,10,3,{BackgroundColor:A_HOUR>5&&A_HOUR<19?0xffffffff:0xff333333,TextColor:A_HOUR>5&&A_HOUR<19?0xff333333:0xffffffff,BorderColor:A_HOUR>5&&A_HOUR<19?0xff333333:0xffffffff,margin:10,Rounded:10,FontSize:13},{Transparent:235,CoordMode:"Screen"})
		SendInput,{/}
	Return

	$Backspace::
		SendInput,{Backspace Down}{Backspace UP}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return

	$,::
		SendInput,{,}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return

	$.::
		SendInput,{.}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return

	$`;::
		SendInput,{`;}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return

	$'::
		SendInput,{'}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return

	$Space::
		SendInput,{Space Down}{Space UP}
		if WinExist("ahk_id " Rbtt.HWND){
			btt("",,,3),EmptyMem()
		}
	Return
#if

#if RBHWND:=WinExist("ahk_id " Rbtt.HWND)
	$Esc::
		btt("",,,3),EmptyMem()
	Return

	$MButton::
		MouseGetPos,,,id
		if (RBHWND=id){
			KeyWait,MButton
			SystemDBClickTime := DllCall("GetDoubleClickTime")
			IfEqual, A_ThisHotkey, %A_PriorHotkey%
			{
				IfLess, A_TimeSincePriorHotkey, %SystemDBClickTime%
				{
					SendInput,{MButton Down}{MButton UP}
					if WinExist("ahk_id " Rbtt.HWND){
						btt("",,,3),EmptyMem()
					}
				}else{
					SendInput,{MButton Down}{MButton UP}
				}
			}else{
				SendInput,{MButton Down}{MButton UP}
			}
		}Else{
			SendInput,{MButton Down}{MButton UP}
		}
	Return
#if
;;===========================================================================================================
GetSymbolsNameList(obj){
	Global symbolsNameArr,symbolsNameList,btt_width
	Count:=1,symbolsNameList:=""

	for Section,element In obj
	{
		if symbolsNameArr[Trim(Section)]
		{
			if (StrLen(symbolsNameList ("〔 " symbolsNameArr[Trim(Section)] "—>" Section " 〕"))>90*Count){
				symbolsNameList.=("〔 " symbolsNameArr[Trim(Section)] "—>" Section " 〕") "`n",Count++
				btt_obj:=btt(symbolsNameList,,,3,{margin:10,Rounded:10,FontSize:13},{JustCalculateSize:1,CoordMode:"Screen"})
				btt_width:=btt_obj.w>btt_width?btt_obj.w:btt_width
			}Else{
				symbolsNameList.=("〔 " symbolsNameArr[Trim(Section)] "—>" Section " 〕")
			}
		}
	}
	if symbolsNameList {
		symbolsNameList.="〔拉丁字符—>/+英文字母〕`n＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝"
			. "`n＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝ Backspace｜Esc｜双击鼠标中键关闭此提示窗口！＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝"
	}
}

CheckVersion(){
	Global ToolVersion
	if DllCall("Wininet.dll\InternetCheckConnection", "Str", "https://www.baidu.com/", "UInt", 0x1, "UInt", 0x0, "Int"){
		URL:="https://gitee.com/leeonchiu/rime-tools-for-wubi98/releases"
		Loop,100
		{
			Version:=Format("{:.2f}", ToolVersion+0.01*A_Index),URL1:=URL "/" Version
			if CheckURL(URL1) {
				Return Version
			}
		}
	}

	Return 0
}

CheckURL(Url){
	ComObjError(0)
	WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	WebRequest.Open("GET", Url)
	WebRequest.Send()

	return (WebRequest.StatusText() = "OK" ? 1 :0)
}
;;==================================================================================================================
;;置顶/取消置顶当前窗口
SetWinTop:
	MouseGetPos, , , Mid
	SetAlwaysOnTop(Mid)
Return

;;置顶Toggle
SetAlwaysOnTop(HWND){
	WinGetClass,WinClass,ahk_id %HWND%
	if (Not WinClass~="i)^(windows.ui.+|Shell_TrayWnd|workerW|NotifyIconOverflowWindow|Program Manager|Progman|ATL\:.+)$"&&WinExist("ahk_id " HWND)){
		WinGet, ExStyle, ExStyle, ahk_id %HWND%
		WinGet, ProcessPath, ProcessPath , ahk_id %HWND%
		FileDescription:=FileGetInfo(ProcessPath, "FileDescription")
		if (ExStyle & 0x8){
			DetectHiddenWindows, On
			WinGetTitle,WinTitle,ahk_id %HWND%
			if (WinTitle&&InStr(WinTitle,"已置顶")){
				WinTitle:=StrReplace(WinTitle,"【已置顶】")
				WinSetTitle, ahk_id %HWND%, , %WinTitle%
			}
			DetectHiddenWindows, Off
			WinSet, AlwaysOnTop, Off, ahk_id %HWND%
			if FileDescription
				TrayTip,%FileDescription%,已取消置顶当前窗口！,,1
		}else{
			DetectHiddenWindows, On
			WinGetTitle,WinTitle,ahk_id %HWND%
			if (WinTitle&&!InStr(WinTitle,"已置顶")){
				WinTitle:=WinTitle . "【已置顶】"
				WinSetTitle, ahk_id %HWND%, , %WinTitle%
			}
			DetectHiddenWindows, Off
			WinSet, AlwaysOnTop, On, ahk_id %HWND%
			if FileDescription
				TrayTip,%FileDescription%,当前窗口已置顶！,,1
		}
	}
}
;;==========================================================系统自启计划任务GUi窗口========================================================
OnAutoTask:
	DefaultFontName:=GetDefaultFontName()
	IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	Gui,AutoTask:Destroy
	Gui,AutoTask:Default
	Gui,AutoTask:+Resize -MaximizeBox +HWNDSetAutoTask
	Gui,AutoTask:Font,% "s9 " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,AutoTask:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,AutoTask:margin,15,15
	SysGet, CXVSCROLL, 2 
	Gui,AutoTask:Add,ListView, r12 w550 AltSubmit Grid +E0x10 -LV0x10 -Multi NoSortHdr -WantF2 0x8 LV0x40  LV0x800 LV0x80 ggetTaskList vTaskList,任务名称|启动文件|附加参数|状态
	LV_ModifyCol(1,150-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,200),LV_ModifyCol(3,120),LV_ModifyCol(4,80 " Center")
	Gosub ReloadList
	Gui,AutoTask:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme ":"BackgroundDefault -Theme ",
	Gui,AutoTask:Show,AutoSize,系统自启计划任务
	ChangeWindowIcon("shell32.dll", WinExist("ahk_id " SetAutoTask), 166)
	CGuiHeight:=0,CGuiWidth:=0
Return

AutoTaskGuiSize:
	if A_Cursor In SizeNESW,SizeNS,SizeNWSE,SizeWE
	{
		GuiControlGet,CGSize,AutoTask:Pos,TaskList
		if (!CGuiHeight&&!CGuiWidth&&CGSizeW>500) {
			Gui, AutoTask:+MinSize%A_GuiWidth%x%A_GuiHeight%
		}else if (CGuiHeight&&CGuiWidth&&CGSizeW>500){
			GuiControlGet,CGSize,AutoTask:Pos,TaskList
			GuiControl,AutoTask:Move,TaskList,% "w" CGSizeW+A_GuiWidth-CGuiWidth " h" CGSizeH+A_GuiHeight-CGuiHeight
			LV_ModifyCol(1,(CGSizeW+A_GuiWidth-CGuiWidth)*0.27-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,(CGSizeW+A_GuiWidth-CGuiWidth)*0.36)
			,LV_ModifyCol(3,(CGSizeW+A_GuiWidth-CGuiWidth)*0.22),LV_ModifyCol(4,(CGSizeW+A_GuiWidth-CGuiWidth)*0.15 " Center")
		}
		CGuiHeight:=A_GuiHeight,CGuiWidth:=A_GuiWidth
	}
Return

getTaskList:
	TaskEventInfo:=0
	if (A_GuiEvent ="RightClick"){
		TaskEventInfo:=A_EventInfo
	}
Return

AutoTaskGuiContextMenu(GuiHwnd, CtrlHwnd, EventInfo, IsRightClick, X, Y){
	if (IsRightClick&&A_GuiControl="TaskList") {
		Menu,ControlTask,Delete
		Menu,ControlTask,Add,刷新列表,ReloadList
		Menu,ControlTask,Add,
		Menu,ControlTask,Add,新增任务,addTask
		Menu,ControlTask,Add,
		Menu,ControlTask,Add,删除任务,DeleteItem
		if !LV_GetNext()
			Menu,ControlTask,Disable,删除任务
		Menu, ControlTask,Show
	}
}

ReloadList:
	Gui,AutoTask:Default
	LV_Delete()
	if TaskInfos:=GetTaskInfos() {
		Loop,Parse, TaskInfos,`n,`r
		{
			TaskPATH:=StrSplit(A_LoopField,"=")
			for key,value In GetTaskActionExecPaths(TaskPATH[1])
				LV_Add(key,TaskPATH[1],value[1],value[2],TaskPATH[2])
		}
	}
Return

DeleteItem:
	Gui,AutoTask:Default
	if (Index:=TaskEventInfo){
		LV_GetText(tname, TaskEventInfo)
		if tname {
			Gui,+OwnDialogs
			MsgBox,262180,删除确认,是否删除该自启任务？
			IfMsgBox,Yes
			{
				if DisableAutorun(tname){
					LV_Delete(Index)
					SB_SetText("< " tname " > - 删除成功！")
				}Else{
					SB_SetText("删除失败！")
				}
				Sleep,1000
				SB_SetText("")
			}
		}
	}
Return

addTask:
	Gui,NewTask:Destroy
	Gui,NewTask:Default
	Gui,NewTask:+OwnerAutoTask -MinimizeBox HWNDAddNewTask
	Gui,NewTask:Font,% "s9 " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,NewTask:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,NewTask:Add,GroupBox,y+15 w350 h200 vGBox1,任务信息
	GuiControlGet,GBox1Pos,NewTask:Pos,GBox1
	Gui,NewTask:Add,Text,% "x" GBox1PosX+15 " y" GBox1PosY+30,任务名称：
	Gui,NewTask:Add,Edit,x+5 yp gControl_Task vSetTaskName HWNDTaskNameEdit,
	EM_SetCueBanner(TaskNameEdit, "任务名称必填！")
	Gui,NewTask:Add,Text,% "x" GBox1PosX+15 " y+15",任务简介：
	Gui,NewTask:Add,Edit,x+5 yp r3 gControl_Task vTaskDescription
	Gui,NewTask:Add,Text,% "x" GBox1PosX+15 " y+20" ,自启文件：
	Gui,NewTask:Add,Edit,x+5 yp r3 gControl_Task vProcessPath HWNDSetProcessPath,
	EM_SetCueBanner(SetProcessPath, "自启文件路径必填！")
	Gui,NewTask:Add,Button,x+10 yp gControl_Task vSelectProcessPath,选择
	Gui,NewTask:Add,Button,xp y+5 gControl_Task vGetProcessPath,识别
	Gui,NewTask:Add,Text,% "x" GBox1PosX+15 " y+20",附加参数：
	Gui,NewTask:Add,Edit,x+5 yp r2 gControl_Task vScriptPath,
	Gui,NewTask:Add,Button,x+10 yp gControl_Task vSelectScriptPath,选择`n文件
	GuiControlGet,SPathPos,NewTask:Pos,SelectScriptPath
	GuiControl,NewTask:Move,GBox1,% "h" SPathPosY-GBox1PosY+SPathPosH+20 " w" SPathPosX-GBox1PosX+SPathPosW+30
	Gui,NewTask:Add,Button,% "xm+12 y" SPathPosY+SPathPosH+30 " w" (SPathPosX-GBox1PosX+SPathPosW) " gControl_Task vSubmitTask Disabled" ,提交任务
	Gui,NewTask:Font,s9
	Gui,NewTask:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme ":"BackgroundDefault -Theme ",
	Gui,NewTask:Show,AutoSize,New Task
	ChangeWindowIcon("shell32.dll", WinExist("ahk_id " AddNewTask), 261)
Return

Control_Task:
	Gui,NewTask:Default
	Gui,NewTask:Submit,NoHide
	Switch A_GuiControl
	{
		case "SetTaskName":
			if SetTaskName&&FileExist(Trim(RegExReplace(ProcessPath,"[\r\n]")))
				GuiControl,NewTask:Enable,SubmitTask
			Else
				GuiControl,NewTask:Disable,SubmitTask
		case "ProcessPath":
			if SetTaskName&&FileExist(Trim(RegExReplace(ProcessPath,"[\r\n]")))
				GuiControl,NewTask:Enable,SubmitTask
			Else
				GuiControl,NewTask:Disable,SubmitTask
		case "SelectProcessPath":
			Gui,+OwnDialogs
			FileSelectFile, filepath, 3, %WeaselRoot%\%ServerExecutable%, 选择启动文件, ProgramFile (*.exe)
			if (filepath <> ""){
				FileDescription:=FileGetInfo(filepath,"FileDescription")
				if (!SetTaskName&&FileDescription)
					GuiControl,NewTask:,SetTaskName,% FileDescription
				if (!Trim(RegExReplace(TaskDescription,"[\r\n]"))&&FileDescription)
					GuiControl,NewTask:,TaskDescription,% FileDescription
				GuiControl,NewTask:,ProcessPath,% filepath
			}
			if SetTaskName
				GuiControl,NewTask:Enable,SubmitTask
			Else
				GuiControl,NewTask:Disable,SubmitTask
		case "GetProcessPath":
			SB_SetText("请15秒内把鼠标放在目标窗口上,按LCtrl确认！")
			keywait, LControl, D T15
			keywait, LControl
			MouseGetPos, , , id
			WinGet, win_exe, ProcessPath, ahk_id %id%
			If win_exe {
				Gui,NewTask:Default
				Gui,NewTask:Submit,NoHide
				FileDescription:=FileGetInfo(win_exe,"FileDescription")
				if (!SetTaskName&&FileDescription)
					GuiControl,NewTask:,SetTaskName,% FileDescription
				if (!Trim(RegExReplace(TaskDescription,"[\r\n]"))&&FileDescription)
					GuiControl,NewTask:,TaskDescription,% FileDescription
				GuiControl,NewTask:,ProcessPath,% win_exe
			}
			if SetTaskName
				GuiControl,NewTask:Enable,SubmitTask
			Else
				GuiControl,NewTask:Disable,SubmitTask
			SB_SetText("")
			WinActivate,ahk_id %AddNewTask%
		case "SelectScriptPath":
			Gui,+OwnDialogs
			FileSelectFile, filepath, 3, , 选择脚本文件, Script File (*.ahk)
			if (filepath <> ""){
				GuiControl,NewTask:,ScriptPath,% filepath
			}
		case "SubmitTask":
			if (FileExist(ProcessPath)&&SetTaskName) {
				if IsAutorunEnabled(SetTaskName){
					Gui,+OwnDialogs
					MsgBox, 262160, Error,任务「%SetTaskName%」已存在！,8
					Return
				}
				flag:=EnableAutoRun(Trim(SetTaskName),Trim(RegExReplace(TaskDescription,"[\r\n]")),Trim(RegExReplace(ProcessPath,"[\r\n]")),RegExReplace(ScriptPath,"[\r\n]"))
				if (flag=Trim(SetTaskName)){
					Gui,AutoTask:Default
					LV_Add(LV_GetCount(),Trim(SetTaskName),Trim(RegExReplace(ProcessPath,"[\r\n]")),RegExReplace(ScriptPath,"[\r\n]"),"Ready")
					Gui,NewTask:Destroy
				}Else if (flag=1){
					MsgBox, 262160, Error,权限不够，添加失败！,8
					Return
				}Else if (flag<0){
					MsgBox, 262160, Error,任务名称和启动文件路径不能为空！,8
					Return
				}
			}
	}
Return

;;====================================================托盘图标提示文字==============================================================
TrayMenuTip:
	Process, Exist , %ServerExecutable%
	Menu,Tray,Tip,% "小狼毫助手v" ToolVersion " - " (A_PtrSize>4?"64bit":"32bit") (ErrorLevel?"`n - 服务进程：运行正常":"`n - 服务进程：Error") (RimeUserDir&&WeaselRoot?"`n - 路径状态：获取正常":"`n - 路径状态：Error") ("`n - Ctrl+鼠标中键->置顶/取消置顶当前窗口")
Return
;;==================================================================================================================
;;===========================================================小狼毫设置窗口=======================================================
OnSetting:
	DefaultFontName:=GetDefaultFontName()
	IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	Gui,Weasel:Destroy
	Gui,Weasel:Default
	Gui,Weasel: +HWNDweaselGui +LastFound
	Gui,Weasel:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Weasel:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,Weasel:Add,GroupBox,y+15 vGroupBox2,候选框参数
	GuiControlGet,gbpos,Weasel:Pos,GroupBox2
	Gui,Weasel:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Weasel:Add,Text,% "x" gbposX+20 " yp+35 vTextInfo1",候选项间距:
	GuiControlGet,gbpos2,Weasel:Pos,TextInfo1
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit3 Center gControl_Weasel vcandidate_spacing",
	Gui,Weasel:Add,UpDown,Range0-300 ,
	GuiControlGet,gbpos3,Weasel:Pos,candidate_spacing
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,候选框横排:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w60 gControl_Weasel vhorizontal Lowercase ",True|False

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+15 w" gbpos2W,编码栏间距:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit3 Center gControl_Weasel vspacing",
	Gui,Weasel:Add,UpDown,Range0-300,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,宽度下限:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit3 Center gControl_Weasel vmin_width",
	Gui,Weasel:Add,UpDown,Range0-300,

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+15 w" gbpos2W,焦点块圆角:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit3 Center gControl_Weasel vround_corner",
	Gui,Weasel:Add,UpDown,Range0-100,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,上下间距:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit4 Center gControl_Weasel vmargin_y",
	Gui,Weasel:Add,UpDown,Range-300-300,

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+15 w" gbpos2W,水平间距:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit4 Center gControl_Weasel vmargin_x",
	Gui,Weasel:Add,UpDown,Range-300-300,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,嵌入编码:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w60 gControl_Weasel vinline_preedit Lowercase ",True|False

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+15 w" gbpos2W,焦点块高度:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit3 Center gControl_Weasel vhilite_padding",
	Gui,Weasel:Add,UpDown,Range0-300,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,候选项字号:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit2 Center gControl_Weasel vfont_point",
	Gui,Weasel:Add,UpDown,Range9-99,


	Gui,Weasel:Add,Text,% "x" gbpos2X " y+15 w" gbpos2W,高度下限:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Center Number Limit3 gControl_Weasel vmin_height",
	Gui,Weasel:Add,UpDown,Range0-300,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,序号间距:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 Center w60 Number Limit3 gControl_Weasel vhilite_spacing",
	Gui,Weasel:Add,UpDown,Range0-300,

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+20 w" gbpos2W,显示图标:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w60 gControl_Weasel vdisplay_tray_icon Lowercase ",True|False
	Gui,Weasel:Add,Text,x+45 yp  w%gbpos2W%,演示模式:
	Gui,Weasel:Add,ddl,x+10 yp-2 Lowercase w60 gControl_Weasel vfullscreen ,True|False

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+20 w" gbpos2W,嵌入方式:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w150 gControl_Weasel vpreedit_type Lowercase ",preview|composition|input
	Gui,Weasel:Add,Checkbox,x+10 yp+2 gControl_Weasel vhide_candidate 0x20,隐藏:

	Gui,Weasel:Add,Text,% "x" gbpos2X " y+20 w" gbpos2W ,更换配色:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 gControl_Weasel vcolor_scheme w150",
	Gui,Weasel:Add,Button,% "x+10 yp-1 gControl_Weasel vchange_theme" ,主题设计
	Gui,Weasel:Add,ddl,% "x" gbpos2X+gbpos2W+10 " y+8 gControl_Weasel vextend_theme_list w150",
	Gui,Weasel:Add,Button,% "x+10 yp-1 gControl_Weasel vsave_extend_theme Disabled" ,添加

	GuiControl,Weasel:Move,GroupBox2,% "w" (gbpos3X+gbpos3W+30)*2 " h" (gbpos3H+28)*8

	Gui,Weasel:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	GuiControlGet,gbpos,Weasel:Pos,GroupBox2
	Gui,Weasel:Add,GroupBox,% "x" gbposX+gbposW+10 " y" gbposY " w" gbposW " h" gbposH " vGroupBox3",方案参数
	GuiControlGet,gbpos4,Weasel:Pos,GroupBox3
	Gui,Weasel:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " yp+35 w" gbpos2W,码长限制:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit2 Center gControl_Weasel vmax_code_length",
	Gui,Weasel:Add,UpDown,Range3-99 ,
	Gui,Weasel:Add,Checkbox,% "x+45 yp+2 gControl_Weasel vauto_select 0x20",候选唯一上屏:

	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " y+20 w" gbpos2W,候选数目:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit2 Center gControl_Weasel vpage_size",
	Gui,Weasel:Add,UpDown,Range1-10 ,
	Gui,Weasel:Add,Text,x+45 yp+2 w%gbpos2W%,逐码提示:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w60 gControl_Weasel venable_completion Lowercase",True|False

	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " y+15 w" gbpos2W,历史候选数:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w60 Number Limit2 Center gControl_Weasel vsize",
	Gui,Weasel:Add,UpDown,Range0-10,

	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " y+15 w" gbpos2W,候选项字体:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w180 gControl_Weasel vfont_face ",% GetFontslist()
	Gui,Weasel:Add,Checkbox,x+20 yp+2 gControl_Weasel vToggle_filter_extend Checked%filter_extend%,

	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " y+20 w" gbpos2W,方案选项:
	Gui,Weasel:Add,ddl,% "x+10 yp-2 w180 gControl_Weasel vswitchelists",
	Gui,Weasel:Add,Checkbox,x+20 yp+2 gControl_Weasel vToggle_State cred,

	Gui,Weasel:Add,Text,% "x" gbpos4X+20 " y+20 w" gbpos2W,同步目录:
	Gui,Weasel:Add,Edit,% "x+10 yp-2 w180 gControl_Weasel vshow_sync_dir ReadOnly",
	Gui,Weasel:Add,Button,x+10 yp gControl_Weasel vselect_sync_dir,更换

	GuiControlGet,Ctpos,Weasel:Pos,change_theme

	Gui,Weasel:Add,Button,% "x" gbpos4X+20 " y+15 gControl_Weasel vSelectSchema" ,方案管理
	Gui,Weasel:Add,Button,x+15 yp gControl_Weasel vset_app_options,窗口状态管理
	Gui,Weasel:Add,Button,x+15 yp-1 gControl_Weasel valternative_select_labels,候选标签设置

	Gui,Weasel:Add,Button,% "x" gbpos4X+20 " y+20 gControl_Weasel vSelectHotkey" ,热键管理
	Gui,Weasel:Add,Checkbox,% "x+20 yp-2 gControl_Weasel vToggle_CapsClear Checked" IsCapsClear,Capslock`n清除编码
	Gui,Weasel:Add,Checkbox,% "x+20 yp gControl_Weasel vToggle_SymbolsTip Checked" IsTip,特殊符号`n输出提示

	Gui,Weasel:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Weasel:Add,Text,% "xm y" gbposY+gbposH+10 " w" gbposW*2+10 " 0x10"
	Gui,Weasel:Add,Button,% "x" gbposW*2-CtposW*2-10 " yp+10 gControl_Weasel vRestPoint Disabled",操作重置
	Gui,Weasel:Add,Button,% "x+15 yp gControl_Weasel vSubmitPoint Disabled",重新部署
	Gui,Weasel:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Weasel:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme gControl_Weasel vWeaselSBar":"BackgroundDefault -Theme gControl_Weasel vWeaselSBar",
	SB_SetParts((gbposW*2+40)*0.8,(gbposW*2+40)*0.2)
	SB_SetText(">>>修改后需点击「重新部署」生效！",1),SB_SetText("`t待部署项：" 0,2,"Center")
	Gui,Weasel:Show,NA AutoSize,% A_IsAdmin?"[管理员] 小狼毫设置":"小狼毫设置"
	Gosub GuiControl_Gui
	WinActivate,ahk_id %weaselGui%
	GuiControl, Weasel:Focus,SelectSchema
	Submit_candidate:={},Submit_Style:={},Submit_switcher:={},Submit_Default:={},Submit_Installation:={},Submit_Themes:=""
	SB_SetText(">>>修改后需点击「重新部署」生效！",1),SB_SetText("`t待部署项：" 0,2,"Center")
Return

GuiControl_Gui:
	DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()
	WeaselYaml_Config:=MatchWeaselItems.GetWeaselYaml()
	CustomSchema_Config:=MatchWeaselItems.GetCustomSchemaConfig(DefaultYaml_Config["schema_list","",1,"schema"])
	InstallationYaml:=MatchWeaselItems.GetInstallationYaml()
	GuiControl,Weasel:,show_sync_dir,% InstallationYaml["sync_dir",1]&&InstallationYaml["installation_id",1]?Trim(InstallationYaml["sync_dir",1],"\") "\" InstallationYaml["installation_id",1]:""

	for key,value In ["font_point","page_size"]
		GuiControl,Weasel:,%value%,% WeaselYaml_Config["style",value]?WeaselYaml_Config["style",value]:CustomSchema_Config["menu",value]
	for key,value In ["candidate_spacing","spacing","min_width","round_corner","margin_y","margin_x","hilite_padding","min_height","hilite_spacing"]
	{
		GuiControl,Weasel:,%value%,% WeaselYaml_Config["style","layout", value]?WeaselYaml_Config["style","layout", value]:0
	}
	for key,value In ["font_face","horizontal","inline_preedit","preedit_type","display_tray_icon","fullscreen"]
	{
		GuiControl,Weasel:ChooseString,%value%,% WeaselYaml_Config["style",value]
	}
	for key,value In ["encode_commit_history","max_phrase_length","enable_sentence","enable_encoder","enable_user_dict","enable_completion"]
	{
		GuiControl,Weasel:ChooseString,%value%,% CustomSchema_Config["translator",value]
	}
	GuiControl,Weasel:,max_code_length,% CustomSchema_Config["speller","max_code_length"]?CustomSchema_Config["speller","max_code_length"]:0
	GuiControl,Weasel:,auto_select,% InStr(CustomSchema_Config["speller","auto_select"],"True")?1:0
	GuiControl,Weasel:,size,% CustomSchema_Config["history","size"]

	if InStr(WeaselYaml_Config["style","inline_preedit"],"True"){
		GuiControl,Weasel:Disable,spacing
		GuiControl,Weasel:Enable,preedit_type
	}Else{
		GuiControl,Weasel:Enable,spacing
		GuiControl,Weasel:Disable,preedit_type
	}
	GuiControl,Weasel:,Toggle_CapsClear,% IsCapsClear?1:0
	GuiControl,Weasel:,Toggle_SymbolsTip,% IsTip?1:0
	GuiControl,Weasel:,hide_candidate,% WeaselYaml_Config["style","layout","margin_x"]<0?1:0
	GuiControl,Weasel:,color_scheme, % GetThemeList(WeaselYaml_Config["preset_color_schemes"])
	GuiControl,Weasel:ChooseString,color_scheme,% WeaselYaml_Config["preset_color_schemes",WeaselYaml_Config["style","color_scheme"],"name"]

	;;自定义预制主题
	extendTheme_object:={black_green:{author: "佚名"
			,back_color: 0x030303
			,border_color: 0x0A0A0A
			,candidate_text_color: 0xF0F0F0
			,comment_text_color: 0x7F908F
			,hilited_back_color: 0x347440
			,hilited_candidate_back_color: 0x347440
			,hilited_candidate_text_color: 0xFFFFFF
			,hilited_text_color: 0xFFFFFF
			,label_color: 0x347440
			,name: "黑底绿／black_green"
			,text_color: 0xF0F0F0
			,hilited_comment_text_color: 0xFBF1E5
			,hilited_candidate_label_color: 0xFBF1E5
			,hilited_label_color: 0xFBF1E5}
		,black_orange:{author: "佚名"
			,back_color: 0x030303
			,border_color: 0x666666
			,candidate_text_color: 0xFFFFFF
			,comment_text_color: 0x7F908F
			,hilited_back_color: 0x1D66CD
			,hilited_candidate_back_color: 0x1D66CD
			,hilited_candidate_label_color: 0xFBF1E5
			,hilited_candidate_text_color: 0xFFFFFF
			,hilited_comment_text_color: 0xFBF1E5
			,hilited_label_color: 0xFBF1E5
			,hilited_text_color: 0xFFFFFF
			,label_color: 0x1D66CD
			,name: "黑底橙／black_orange"
			,text_color: 0xFAFAFF}
		,black_blue:{author: "佚名"
			,back_color: 0x000000
			,border_color: 0x666666
			,candidate_text_color: 0xFCFCFC
			,comment_text_color: 0x7F908F
			,hilited_back_color: 0xCD661D
			,hilited_candidate_back_color: 0xCD661D
			,hilited_candidate_label_color: 0xFBF1E5
			,hilited_candidate_text_color: 0xFFFFFF
			,hilited_comment_text_color: 0xFFE6BF
			,hilited_label_color: 0xFBF1E5
			,hilited_text_color: 0xFFFFFF
			,label_color: 0xCD661D
			,name: "黑底蓝／black_blue"
			,text_color: 0xFBF1E5}
		,black_red: {author: "佚名"
			,back_color: 0x000000
			,border_color: 0x666666
			,candidate_text_color: 0xFFFFFF
			,comment_text_color: 0x7F908F
			,hilited_back_color: 0x4734D6
			,hilited_candidate_back_color: 0x4734D6
			,hilited_candidate_label_color: 0xFBF1E5
			,hilited_candidate_text_color: 0xFFFFFF
			,hilited_comment_text_color: 0xFBF1E5
			,hilited_label_color: 0xFBF1E5
			,hilited_text_color: 0xFFFFFF
			,label_color: 0x7F908F
			,name: "黑底红／black_red"
			,text_color: 0xFAFAFF}
		,black_gold: {author: "佚名"
			,back_color: 0x282828
			,border_color: 0x383C41
			,candidate_text_color: 0xB2DBEB
			,comment_text_color: 0x748392
			,hilited_back_color: 0x8499A8
			,hilited_candidate_back_color: 0x454950
			,hilited_candidate_text_color: 0xC7F1FB
			,hilited_text_color: 0x282828
			,name: "黑底金／black_gold"
			,text_color: 0x8499A8
			,label_color: 0x748392}}
	GuiControl,Weasel:,extend_theme_list, % GetExtendThemeList(extendTheme_object)

	if objCount(switches_list:=objCount(switches_list)?switches_list:GetSwitcherAllList()){
		GuiControl,Weasel:,switchelists,% SwitcherNamelist:=GetSwitcherName(switches_list)
		GuiControl,Weasel:Choose,switchelists,1
		GuiControl,Weasel:,Toggle_State,% Trim(switches_list[1,"reset"])
	}Else{
		GuiControl,Weasel:Disable,switchelists
		GuiControl,Weasel:Disable,Toggle_State
	}

	if objCount(CustomSchema_Config["punctuator","symbols"]){
		GetSymbolsNameList(CustomSchema_Config["punctuator","symbols"])
	}
Return

GetExtendSchemaId(){
	Global DefaultYaml_Config,RimeUserDir,WeaselRoot
	if !objCount(DefaultYaml_Config["schema_list",""])
		DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()

	for Section,element In DefaultYaml_Config["schema_list",""]
	{
		DictPath:= FileExist(RimeUserDir "\" element["schema"] ".dict.yaml")?RimeUserDir "\" element["schema"] ".dict.yaml":WeaselRoot "\data\" element["schema"] ".dict.yaml"
		FileContent:=GetFileContent(DictPath)
		if FileContent~="[" Chr(0x2b820) "-" Chr(0x3134a) "]"{
			Return element["schema"]
		}
	}
}
;;获取所有方案Switcher开关组项目
GetSwitcherAllList(){
	Global DefaultYaml_Config
	switches_list:={}
	for Section,element In DefaultYaml_Config["schema_list",""]
	{
		for key,value In MatchWeaselItems.GetCustomSchemaConfig(element["schema"])["switches",""]
		{
			if !IsExistSwitchesName(switches_list,value["name"])
				switches_list.Push(value)
		}
	}
	Return switches_list
}

GetSwitcherName(obj){
	Static switcherName
	switcherName:=""

	if !objCount(obj)
		Return
	for Section,element In obj
	{
		switcherName.="|" Trim(element["name"]) (element["states"]?"／" element["states"]:"")
	}

	Return switcherName
}

IsExistSwitchesName(obj,item){
	for Section,element In obj
		if (element["name"]=item)
			Return element["name"]
}

GetThemeList(obj){
	Global ThemeList
	Static List
	List:=""
	ThemeList:={}
	for Section,element In obj
	{
		List.="|" Trim(element["name"]), ThemeList[Trim(element["name"])]:=Section
	}

	Return List
}

GetExtendThemeList(obj){
	Global ExtendThemeList
	Static List
	List:=""
	ExtendThemeList:={}
	for Section,element In obj
	{
		List.="|" Trim(element["name"]), ExtendThemeList[Trim(element["name"])]:=Section
	}

	Return List
}

Control_Weasel:
	Gui,Weasel:Default
	GuiControlGet, FocusControl, FocusV
	if FocusControl {
		Switch A_GuiControl
		{
			case "candidate_spacing","spacing","min_width","round_corner","margin_y","margin_x","hilite_padding","min_height","hilite_spacing":
				Gui,Weasel:Submit,NoHide
				Submit_Style["style/layout/" A_GuiControl]:=MatchWeaselItems.StringLower(%A_GuiControl%)
			case "font_face","horizontal","font_point","inline_preedit","preedit_type","color_scheme","display_tray_icon","fullscreen":
				Gui,Weasel:Submit,NoHide
				if (A_GuiControl="color_scheme"){
					GuiControl,Weasel:Choose,extend_theme_list,0
					if objCount(ThemeList){
						Submit_Style["style/" A_GuiControl]:= Trim(ThemeList[%A_GuiControl%])
						if (objCount(presetTheme:=WeaselYaml_Config["preset_color_schemes",Trim(ThemeList[%A_GuiControl%])])){
							ShowPreviewGui()
						}
						DetectHiddenWindows,Off
						if WinExist("ahk_id " previewTheme){
							if !objCount(PreviewDock){
								PreviewDock := new Dock(weaselGui, previewTheme)
								PreviewDock.Position("L")
								PreviewDock.CloseCallback := Func("CloseCallback")
							}
							Control_previewColor(presetTheme:=WeaselYaml_Config["preset_color_schemes",Trim(ThemeList[%A_GuiControl%])])
						}
					}
				}Else if (A_GuiControl="font_face"&&filter_extend){
					ExtendSchemaId:=ExtendSchemaId?ExtendSchemaId:GetExtendSchemaId()
					if ExtendSchemaId {
						Submit_Style["style/" A_GuiControl]:=[%A_GuiControl%,ExtendSchemaId]
					}Else{
						Submit_Style["style/" A_GuiControl]:=%A_GuiControl%
					}
				}Else{
					Submit_Style["style/" A_GuiControl]:=MatchWeaselItems.StringLower(%A_GuiControl%)
				}
				if (%A_GuiControl%="True"&&A_GuiControl="inline_preedit"){
					GuiControl,Weasel:Disable,spacing
					GuiControl,Weasel:Enable,preedit_type
					for Section,element In {"style/layout/margin_y":12,"style/layout/candidate_spacing":InStr(WeaselYaml_Config["style","horizontal"],"True")||InStr(Submit_Style["style/horizontal"],"True")?18:15,"style/layout/margin_x":12,"style/layout/round_corner":0,"style/layout/hilite_padding":12,"style/layout/spacing":18}
					{
						Submit_Style[Section]:=element
						GuiControl,Weasel:,% RegExReplace(Section,".+\/"),% element
					}
				}Else if (%A_GuiControl%="False"&&A_GuiControl="inline_preedit"){
					GuiControl,Weasel:Enable,spacing
					GuiControl,Weasel:Disable,preedit_type
					for Section,element In {"style/layout/margin_y":12,"style/layout/candidate_spacing":InStr(WeaselYaml_Config["style","horizontal"],"True")||InStr(Submit_Style["style/horizontal"],"True")?20:18,"style/layout/margin_x":12,"style/layout/round_corner":4,"style/layout/hilite_padding":6,"style/layout/spacing":26}
					{
						Submit_Style[Section]:=element
						GuiControl,Weasel:,% RegExReplace(Section,".+\/"),% element
					}
				}
			case "Toggle_filter_extend":
				Gui,Weasel:Submit,NoHide
				filter_extend:=ConfigObject["filter_extend"]:=!filter_extend
				Try {
					Json_ObjToFile(ConfigObject, A_AppData "\RimeToolData\Weasel\Weasel.Json", "utf-8")
				}
				if filter_extend {
					if Submit_Style["style/font_face"]{
						ExtendSchemaId:=ExtendSchemaId?ExtendSchemaId:GetExtendSchemaId()
						if ExtendSchemaId {
							Submit_Style["style/font_face"]:=[Submit_Style["style/font_face"],ExtendSchemaId]
						}
					}else{
						ExtendSchemaId:=ExtendSchemaId?ExtendSchemaId:GetExtendSchemaId()
					}
				}Else{
					if objCount(Submit_Style["style/font_face"]){
						Submit_Style["style/font_face"]:=Submit_Style["style/font_face",1]
					}
				}
			case "max_code_length","auto_select":
				Gui,Weasel:Submit,NoHide
				Submit_candidate["speller/auto_clear"]:="max_length"
				Submit_candidate["speller/" A_GuiControl]:=A_GuiControl="auto_select"?%A_GuiControl%?"true":"false":%A_GuiControl%
			case "size","input":
				Gui,Weasel:Submit,NoHide
				Submit_candidate["history/" A_GuiControl]:=%A_GuiControl%
			case "enable_completion":
				Gui,Weasel:Submit,NoHide
				Submit_candidate["translator/" A_GuiControl]:=MatchWeaselItems.StringLower(%A_GuiControl%)
			case "page_size":
				Gui,Weasel:Submit,NoHide
				Submit_candidate["menu/" A_GuiControl]:=MatchWeaselItems.StringLower(%A_GuiControl%)
			case "hide_candidate":
				Gui,Weasel:Submit,NoHide
				for Section,element in {"style/layout/margin_x":hide_candidate?-300:12,"style/layout/margin_y":hide_candidate?-300:12}
				{
					Submit_Style[Section]:=element
					GuiControl,Weasel:,% RegExReplace(Section,".+\/"),% element
				}
			case "SubmitPoint":
				flag:=0
				TrayTip,小狼毫助手,配置修改中，请稍候！,,1
				if objCount(Submit_Style){
					if MatchWeaselItems.ModifyWeaselYaml(Submit_Style){
						flag++
					}
				}
				if objCount(Submit_candidate){
					if MatchWeaselItems.ModifyCustomYaml(Submit_candidate){
						flag++
					}
				}
				if objCount(Submit_switcher){
					if MatchWeaselItems.ModifySwitcherState(Submit_switcher){
						flag++
					}
				}
				if objCount(Submit_Default){
					if MatchWeaselItems.ModifyDefaultYaml(Submit_Default){
						flag++
					}
				}
				if objCount(Submit_Installation){
					if MatchWeaselItems.ModifyInstallationYaml(Submit_Installation){
						flag++
					}
				}
				if Submit_Themes {
					if MatchWeaselItems.AppendColorThemes(Submit_Themes){
						flag++
					}
				}

				if flag
					MatchWeaselItems.DeployWeasel()
				Submit_candidate:={},Submit_Style:={},Submit_switcher:={},Submit_Default:={},Submit_Installation:={},Submit_Themes:=""
			case "alternative_select_labels":
				if Items:=SetParameterGui("候选项序号更改","请输入至少9个字符！", , ,1,,"Weasel",weaselGui){
					Items:=Split_Select_labels(Items)
					if (Items=-1)
						TrayTip,小狼毫助手,不符合要求，至少得9个字符！,,2
					Else
						Submit_candidate["menu/" A_GuiControl]:=Items
				}
			case "set_app_options":
				Gosub OnAppOptions
			case "change_theme":
				Gosub options_color_scheme
			case "switchelists":
				Gui,Weasel:Submit,NoHide
				GuiControl,Weasel:,Toggle_State,
				GuiControl,Weasel:,Toggle_State,% GetSwitchesReset(CustomSchema_Config["switches",""],Trim(RegExReplace(switchelists,"\／.+")))
			case "Toggle_State":
				Gui,Weasel:Submit,NoHide
				Submit_switcher[Trim(RegExReplace(switchelists,"\／.+"))]:=Toggle_State
				GuiControl,Weasel:,Toggle_State,% Toggle_State?"√":"×"
				Sleep,500
				GuiControl,Weasel:,Toggle_State,
			case "RestPoint":
				Gosub GuiControl_Gui
				Submit_candidate:={},Submit_Style:={},Submit_switcher:={},Submit_Default:={},Submit_Installation:={},Submit_Themes:=""
				GuiControl,Weasel:Disable,SubmitPoint
				GuiControl,Weasel:Disable,RestPoint
			case "SelectSchema":
				DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()
				Gui,schema:Destroy
				Gui,schema:Default
				IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
				Gui,schema: -MaximizeBox -MinimizeBox OwnerWeasel -DPIScale  HWNDSelectSchemaList
				Gui,schema:margin,,20
				Gui,schema:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
				Gui,schema:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
				Gui,schema:Add,ListBox,r10 w100 gControl_Schema vShowSchemalistbox_left,% GetRimeSchemalist()
				GuiControlGet,lbpos,schema:Pos,ListBox1
				Gui,schema:Add,Text,x+20 ym h%lbposH% 0x11,
				Gui,schema:Add,ListBox,xp+20 ym r10 w100 gControl_Schema vShowSchemalistbox_right,
				Gui,schema:Show,AutoSize ,方案选择
				WinActivate,ahk_id %SelectSchemaList%
				GuiControl,schema:,ShowSchemalistbox_right,% GetSchemaActionList()
				IsChange:=0

				Return
			case "SelectHotkey":
				DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()
				Gui,Hotkey:Destroy
				Gui,Hotkey:Default
				IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
				Gui,Hotkey: -MaximizeBox -MinimizeBox OwnerWeasel -DPIScale  HWNDSelectHotkeyList
				Gui,Hotkey:margin,,20
				Gui,Hotkey:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
				Gui,Hotkey:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
				Gui,Hotkey:Add,ListBox,r10 w220 gControl_Hotkey vShowHotkeylistbox,
				GuiControlGet,lbpos,Hotkey:Pos,ListBox1
				Gui,Hotkey:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
				Gui,Hotkey:Add,Text,% " xm y" lbposY+lbposH+12 " vTextInfo3",Caption:
				GuiControlGet,Textpos,Hotkey:Pos,TextInfo3
				Gui,Hotkey:Add,Edit,% "x+10 yp-2 w" lbposW-TextposW-10 " gControl_Hotkey vCaption",
				Gui,Hotkey:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
				Gui,Hotkey:Add,Button,% "w" (lbposW-10)/2 " xm y+10 gControl_Hotkey vAddWeaselHotkey",添加热键
				Gui,Hotkey:Add,Button,% "w" (lbposW-10)/2 " x+10 yp gControl_Hotkey vCancelOption",操作重置
				SetButtonColor("AddWeaselHotkey","0xf0f0f0","Hotkey"),SetButtonColor("CancelOption","0xf0f0f0","Hotkey")
				Gui,Hotkey:Show,AutoSize ,小狼毫热键设置
				Gosub GuiControl_hotkey

				Return
			case "Toggle_CapsClear":
				Gui,Weasel:Submit,NoHide
				IsCapsClear:=ConfigObject["IsCapsClear"]:=!IsCapsClear
				Try {
					Json_ObjToFile(ConfigObject, A_AppData "\RimeToolData\Weasel\Weasel.Json", "utf-8")
				}
			case "Toggle_SymbolsTip":
				Gui,Weasel:Submit,NoHide
				IsTip:=ConfigObject["IsTip"]:=!IsTip
				Try {
					Json_ObjToFile(ConfigObject, A_AppData "\RimeToolData\Weasel\Weasel.Json", "utf-8")
				}
			case "select_sync_dir":
				Gui,Weasel:Submit,NoHide
				Gui,+OwnDialogs
				FileSelectFolder, sync_folder, , 3,请选择一个目录作为同步目录
				if sync_folder~="[\x00-\xff]+\\[\x00-\xff]+\\[\x00-\xff]+" {
					Submit_Installation["sync_dir"]:=RegExReplace(sync_folder,"(?<=\\)[^\\]+$"),Submit_Installation["installation_id"]:=RegExReplace(sync_folder,".+\\")
					GuiControl,Weasel:,show_sync_dir,% sync_folder
				}else if sync_folder~="[^\x00-\xff]"{
					Gui,+OwnDialogs
					MsgBox, 262160,Error,路径不能包含中文字符,15
					Return
				}else if sync_folder{
					Gui,+OwnDialogs
					MsgBox, 262160,Error,路径至少为磁盘下两层目录,15
					Return
				}
			case "extend_theme_list":
				Gui,Weasel:Submit,NoHide
				if InStr(GetFileContent(RimeUserDir "\weasel.custom.yaml"),"preset_color_schemes/" extendthemelist[%A_GuiControl%])||InStr(Submit_Themes,"preset_color_schemes/" extendthemelist[%A_GuiControl%])
					GuiControl,Weasel:Disable,save_extend_theme
				Else
					GuiControl,Weasel:Enable,save_extend_theme

				if (objCount(presetExtendTheme:=extendTheme_object[extendthemelist[%A_GuiControl%]])){
					ShowPreviewGui(0,1)
				}
				DetectHiddenWindows,Off
				if WinExist("ahk_id " previewTheme){
					if !objCount(PreviewDock){
						PreviewDock := new Dock(weaselGui, previewTheme)
						PreviewDock.Position("L")
						PreviewDock.CloseCallback := Func("CloseCallback")
					}
					Control_previewColor(presetExtendTheme:=extendTheme_object[extendthemelist[%A_GuiControl%]])
				}
			case "save_extend_theme":
				Gui,Weasel:Submit,NoHide
				if objCount(presetExtendTheme)&&FileExist(RimeUserDir){
					if themeInfo:=FormatThemeObject(extendthemelist[extend_theme_list],presetExtendTheme){
						ThemeList[extend_theme_list]:=extendthemelist[extend_theme_list],Submit_Themes.=themeInfo "`r`n"
						WeaselYaml_Config["preset_color_schemes",extendthemelist[extend_theme_list]]:=presetExtendTheme
						GuiControl,Weasel:,color_scheme,% extend_theme_list
					}
				}
				GuiControl,Weasel:Disable,save_extend_theme
		}
		Gosub Control_Weasel_last
	}
Return

FormatThemeObject(itemName,obj){
	Static List
	List:=""
	if itemName&&objCount(obj) {
		for Section,element In obj
		{
			List.="    " Section ":" A_Space Trim(element~="i)^\d+$|^0x[a-fA-F0-9]{3,6}$"?Format("0x{:06X}",element):"""" element """") "`r`n"
		}
		List:=List?A_Space A_Space """" . "preset_color_schemes/" . itemName . """" . ":" . "`r`n" . List:""
	}

	Return List
}

ShowPreviewGui(Cancel=0,ext=0){
	Global
	DetectHiddenWindows,On
	if !WinExist("ahk_id " previewTheme){
		Try {
			Gui,preview:Destroy
			Gui,preview:Default
			IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
			DefaultFontName:=GetDefaultFontName(),previewWidth:=155,previewHeight:=300
			Gui,preview: -Caption HWNDpreviewTheme
			Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
			Gui,preview: Add, Pic,% " x0 y0 w" previewWidth " h" previewHeight "  vborder_color_preview", % "HBITMAP:" . CreateColoredBitmap(previewWidth, previewHeight, 0x000000)
			Gui,preview: Add, Pic,% "xp+5 yp+5 w" previewWidth-10 " h" previewHeight-10 "  vback_color_preview", % "HBITMAP:" . CreateColoredBitmap(previewWidth-10, previewHeight-10, 0x333333)

			Gui,preview: Add, Text,% "xp+12 yp+8 BackgroundTrans  vtext_color_preview cffffff", 小狼毫
			Gui,preview: Add, Pic,% "x+8 yp w60 h18  vhilited_back_color_preview ", % "HBITMAP:" . CreateColoredBitmap(30, 15, 0xe81010)
			Gui,preview: Add, Text,% "xp+4 yp BackgroundTrans  vhilited_text_color_preview cffffff", pei'se
			GuiControlGet,htcppos,preview:Pos,hilited_text_color_preview
			GuiControl,preview:Move,hilited_back_color_preview,% "w" htcpposW+10 " h" htcpposH+5

			GuiControlGet,BCPos,preview:Pos,back_color_preview
			GuiControlGet,TCPos,preview:Pos,text_color_preview
			Gui,preview: Add, Pic,% "x" BCPosX+8 " y+15 w" BCPosW-16 " h" TCPosH+10 "  vhilited_candidate_back_color_preview ", % "HBITMAP:" . CreateColoredBitmap(BCPosW-16, TCPosH+10, 0xe81010)
			Gui,preview: Add, Text,% "xp+2 yp+5 BackgroundTrans  vhilited_label_color_preview cf0f0f0" , 1.

			Gui,preview: Add, Text,% "x+4 yp BackgroundTrans   vhilited_candidate_text_color_preview cffffff" , 配色
			Gui,preview: Add, Text,% "x+30 yp BackgroundTrans   vhilited_comment_text_color_preview cf0f0f0",sgqc

			GuiControlGet,hlcpos,preview:Pos,hilited_label_color_preview
			GuiControlGet,hctpos,preview:Pos,hilited_candidate_text_color_preview
			GuiControlGet,hctpos2,preview:Pos,hilited_comment_text_color_preview
			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview1 ce81010" , 2.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview1 cffffff" , 陪
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview1 cffffff", bukg

			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview2 ce81010" , 3.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview2 cffffff" , 配
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview2 cffffff" , sgnn

			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview3 ce81010" , 4.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview3 cffffff" , 赔
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview3 cffffff" , mukg

			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview4 ce81010" , 5.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview4 cffffff" , 培
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview4 cffffff" , fukg

			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview5 ce81010" , 6.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview5 cffffff" , 佩
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview5 cffffff" , wwgh

			Gui,preview: Add, Text,% "x" hlcposX " y+15 BackgroundTrans  vlabel_color_preview6 ce81010" , 7.
			Gui,preview: Add, Text,% "x+4 w" hctposW " yp BackgroundTrans  vcandidate_text_color_preview6 cffffff" , 呸
			Gui,preview: Add, Text,% "x" hctpos2X " yp BackgroundTrans  vcomment_text_color_preview6 cffffff" , kdhg
			if Cancel {
				Gui,preview:Cancel
			}Else{
				Control_previewColor(ext?presetExtendTheme:objCount(presetTheme)?presetTheme:presetExtendTheme)
				if WinExist("ahk_id " weaselGui){
					Gui,preview:+OwnerWeasel
					WinGetPos,xpos,ypos,Width,Height,ahk_id %weaselGui%
					Gui,preview:Show,% " w" previewWidth " h" previewHeight " x" xpos-previewWidth*(A_ScreenDPI/96) " y" ypos,主题预览
					;;DllCall("SetParent", "uint", previewTheme, "uint", weaselGui)
				}Else{
					Gui,preview:Show,% " w" previewWidth " h" previewHeight,主题预览
				}
			}
		}Catch{
			MsgBox,262160,Error,预览窗口初始化加载失败,5
		}
	}Else if WinExist("ahk_id " previewTheme)&&!Cancel {
		Control_previewColor(ext?presetExtendTheme:objCount(presetTheme)?presetTheme:presetExtendTheme)
		if WinExist("ahk_id " weaselGui){
			Gui,preview:+OwnerWeasel
			WinGetPos,xpos,ypos,Width,Height,ahk_id %weaselGui%
			Gui,preview:Show,% " w" previewWidth " h" previewHeight " x" xpos-previewWidth*(A_ScreenDPI/96) " y" ypos,主题预览
			;;DllCall("SetParent", "uint", previewTheme, "uint", weaselGui)
		}Else{
			Gui,preview:Show,% " w" previewWidth " h" previewHeight,主题预览
		}
	}
	if !ext {
		GuiControl,Weasel:Choose,extend_theme_list,0
		GuiControl,Weasel:Disable,save_extend_theme
	}
	DetectHiddenWindows,Off
	if WinExist("ahk_id " previewTheme){
		Return previewTheme
	}
}

Control_previewColor(ColorArr){
	Global
	Gui,preview:Default
	if objCount(ColorArr){
		for Section,element In ["back_color","border_color","text_color","hilited_text_color","hilited_back_color","hilited_candidate_back_color","hilited_candidate_text_color","hilited_comment_text_color","candidate_text_color","comment_text_color","label_color","hilited_candidate_label_color","hilited_label_color"]
		{
			Switch element
			{
				case "back_color":
					GuiControl,preview:, back_color_preview,% "HBITMAP:" . CreateColoredBitmap(previewWidth, previewHeight,FormatColor_BGR(ColorArr[element]))
				case "border_color":
					GuiControl,preview:, border_color_preview,% "HBITMAP:" . CreateColoredBitmap(previewWidth, previewHeight,FormatColor_BGR(ColorArr[element]))
				case "text_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["candidate_text_color"]<>""?ColorArr["candidate_text_color"]:0xffffff
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					GuiControl,preview:Font,%element%_preview
				case "hilited_back_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["back_color"]
					GuiControl,preview:, hilited_back_color_preview,% "HBITMAP:" . CreateColoredBitmap(previewWidth, previewHeight,FormatColor_BGR(ColorArr[element]))
				case "hilited_text_color":
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					GuiControl,preview:Font,%element%_preview
				case "hilited_label_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["hilited_candidate_text_color"]<>""?ColorArr["hilited_candidate_text_color"]:ColorArr["label_color"]
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					GuiControl,preview:Font,%element%_preview
				case "candidate_text_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["text_color"]<>""?ColorArr["text_color"]:0xffffff
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					Loop,6
						GuiControl,preview:Font,%element%_preview%A_Index%
				case "comment_text_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["candidate_text_color"]
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					Loop,6
						GuiControl,preview:Font,%element%_preview%A_Index%
				case "label_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["candidate_text_color"]
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					Loop,6
						GuiControl,preview:Font,%element%_preview%A_Index%
				case "hilited_candidate_back_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["back_color"]
					GuiControl,preview:, hilited_candidate_back_color_preview,% "HBITMAP:" . CreateColoredBitmap(previewWidth, previewHeight,FormatColor_BGR(ColorArr[element]))
				case "hilited_candidate_text_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["candidate_text_color"]
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					GuiControl,preview:Font,%element%_preview
				case "hilited_comment_text_color":
					ColorArr[element]:=ColorArr[element]<>""?ColorArr[element]:ColorArr["hilited_candidate_text_color"]<>""?ColorArr["hilited_candidate_text_color"]:ColorArr["candidate_text_color"]
					Gui,preview:Font,% "s11 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(ColorArr[element]),3),% DefaultFontName
					GuiControl,preview:Font,%element%_preview
			}
		}
		WinActivate,ahk_id %weaselGui%
	}
}

GetSwitchesReset(obj,name){
	for Section,element in obj
	{
		if (element["name"]=name)
			Return element["reset"]
	}

	Return 0
}
;;=====================================================switches热切换热键设置=============================================================
GuiControl_hotkey:
	GuiControl,Hotkey:,ShowHotkeylistbox,% "|" GetRimeHotkeylist()
	GuiControl,Hotkey:,Caption,% DefaultYaml_Config["switcher","Caption"]
	IsChangeHotkey:=0
Return

Control_Hotkey:
	Gui,Hotkey:Default
	Switch A_GuiControl
	{
		case "ShowHotkeylistbox":
			Gui,Hotkey:Submit,NoHide
			if (A_GuiEvent="doubleClick"){
				IsChangeHotkey++
				ControlGet, Hotkeylistbox1, List , , listBox1, ahk_id %SelectHotkeyList%
				GuiControl,Hotkey:,ShowHotkeylistbox,% RegExReplace(StrReplace("`n" Trim(Hotkeylistbox1,"`n"),"`n" ShowHotkeylistbox),"`n","|")
			}
		case "AddWeaselHotkey":
			Gui,Hotkey:Submit,NoHide
			ControlGet, Hotkeylistbox1, List , , listBox1, ahk_id %SelectHotkeyList%
			Gui,+OwnDialogs
			MsgBox,262180,操作确认,Alt｜Shift｜Ctrl是否区分左右？
			IfMsgBox,Yes
			{
				SetButtonColor(A_GuiControl,"0xe81010","Hotkey")
				if ComboKey:=Format_hotkey_Unix(Format_hotkey(WaitComboKey("T15"))){
					if !InStr("`n" Hotkeylistbox1 "`n", "`n" ComboKey "`n"){
						IsChangeHotkey++
						GuiControl,Hotkey:,ShowHotkeylistbox,% ComboKey
					}
				}
			}Else{
				SetButtonColor(A_GuiControl,"0xe81010","Hotkey")
				if ComboKey:=Format_hotkey_Unix(Format_hotkey(WaitComboKey("T15"),1)){
					if !InStr("`n" Hotkeylistbox1 "`n", "`n" ComboKey "`n"){
						IsChangeHotkey++
						GuiControl,Hotkey:,ShowHotkeylistbox,% ComboKey
					}
				}
			}
			SetButtonColor(A_GuiControl,"0xf0f0f0","Hotkey")
		case "CancelOption":
			IsChangeHotkey:=0
			Gosub GuiControl_hotkey
		case "Caption":
			Gui,Hotkey:Submit,NoHide
			if (DefaultYaml_Config["switcher","Caption"]<>Caption)
				IsChangeHotkey++
	}
Return

HotkeyGuiClose:
	Gui,Hotkey:Default
	Gui,Hotkey:Submit,NoHide
	if IsChangeHotkey {
		ControlGet, Hotkeylistbox1, List , , listBox1, ahk_id %SelectHotkeyList%
		if objCount(obj:=strSplit(Trim(Hotkeylistbox1,"`n"),"`n"))&&Trim(Caption){
			Submit_Default["switcher\hotkeys"]:=obj
			Submit_Default["switcher\caption"]:=Trim(Caption)
			Gosub Control_Weasel_last
			DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()
		}
	}
	IsChangeHotkey:=0
	Gui,Hotkey:Destroy
Return

Format_hotkey_Unix(hk){
	FormatUnixHk:= {Ctrl: ["Control"],enter: ["Return"],esc: ["Escape"],Pgup: ["Prior","Page_Up"],Pgdn: ["Next","Page_Down"]
		,LShift: ["Shift_L"],RShift: ["Shift_R"],LCtrl: ["Control_L"],RCtrl: ["Control_R"],LAlt: ["Alt_L"]
		,RAlt: ["Alt_R"],CapsLock: ["Caps_Lock"],ScrollLock: ["Scroll_Lock"],NumLock: ["Num_Lock"],PrintScreen: ["Print"]
		,AppsKey: ["Menu"],"'": ["apostrophe"],",": ["comma"],"-": ["minus"],".": ["period"],"/": ["slash"]
		,"`;": ["semicolon"],"=": ["equal"],"\": ["backslash"],"``": ["grave"],"[": ["bracketleft"],"]": ["bracketright"]}
	UnixHk:=""
	Loop,% objCount(tarr:=strSplit(hk,"+"))
	{
		UnixHk.=(FormatUnixHk[Trim(tarr[A_Index]),1]?FormatUnixHk[Trim(tarr[A_Index]),1]:Trim(tarr[A_Index])) . "+"
	}

	Return Trim(UnixHk,"+")
}

GetRimeHotkeylist(){
	Global DefaultYaml_Config
	HotkeyList:=""
	for Section,element in DefaultYaml_Config["switcher","hotkeys",""]
	{
		HotkeyList.= element "|"
	}

	Return Trim(HotkeyList,"|")
}

GetSchemaActionList(){
	Global DefaultYaml_Config,schemaIdObject
	Static List
	List:=""
	for Section,element in DefaultYaml_Config["schema_list",""]
		if schemaIdObject[Trim(element["schema"])]
			List.=schemaIdObject[Trim(element["schema"])] "|"

	Return Trim(List,"|")
}

Format_hotkey(hk,flag=0){
	hk:=RegExReplace(hk,"\+","Shift+")
	hk:=RegExReplace(hk,"\^","Ctrl+")
	hk:=RegExReplace(hk,"\!","Alt+")
	hk:=RegExReplace(hk,"\#","Win+")
	hk:=RegExReplace(hk,"\<",flag?"":"L")
	hk:=RegExReplace(hk,"\>",flag?"":"R")

	Return hk
}

Format_hotkey2(hk){
	hk:=RegExReplace(hk,"\s+"),keylist:=""
	if (Index:=objCount(tarr:=StrSplit(hk,"+")))&&hk~="[^\!\+\#\<\>]\+[^\!\+\#\<\>]"{
		Loop,% Index
		{
			Switch tarr[A_Index]
			{
				Case "LCtrl","RCtrl","LControl","RControl","Ctrl","Control":
					keylist.=Index>A_Index?(InStr(tarr[A_Index],"LC")?"<^":InStr(tarr[A_Index],"RC")?">^":"^"):tarr[A_Index]
				Case "LShift","RShift","Shift":
					keylist.=Index>A_Index?(InStr(tarr[A_Index],"LS")?"<+":InStr(tarr[A_Index],"RS")?">+":"+"):tarr[A_Index]
				Case "LAlt","RAlt","Alt":
					keylist.=Index>A_Index?(InStr(tarr[A_Index],"LA")?"<!":InStr(tarr[A_Index],"RA")?">!":"!"):tarr[A_Index]
				Case "LWin","RWin","Win":
					keylist.=Index>A_Index?(InStr(tarr[A_Index],"LW")?"<#":InStr(tarr[A_Index],"RW")?">#":"<#"):tarr[A_Index]
				Default:
					keylist.=tarr[A_Index]
			}
		}
		Return keylist
	}

	Return hk
}
;;==================================================================================================================

Control_Weasel_last:
		Gui,Weasel:Default
		SB_SetText("`t待部署项：" objCount(Submit_candidate)+objCount(Submit_Style)+objCount(Submit_switcher)+objCount(Submit_Default)+objCount(Submit_Installation)+(Submit_Themes?1:0),2,"Center")
		if (objCount(Submit_Style)||objCount(Submit_candidate)||objCount(Submit_switcher)||objCount(Submit_Default)||objCount(Submit_Installation)||Submit_Themes){
			GuiControl,Weasel:Enable,SubmitPoint
			GuiControl,Weasel:Enable,RestPoint
		}Else{
			GuiControl,Weasel:Disable,SubmitPoint
			GuiControl,Weasel:Disable,RestPoint
		}
		GuiControl, Weasel:Focus,SelectSchema
		EmptyMem()
Return

Control_Schema:
	Gui,schema:Default
	Switch A_GuiControl
	{
		case "ShowSchemalistbox_left":
			Gui,schema:Submit,NoHide
			if (A_GuiEvent="doubleClick"){
				ControlGet, Schemalistbox2, List , , listBox2, ahk_id %SelectSchemaList%
				if ShowSchemalistbox_left&&!InStr("`n" Schemalistbox2 "`n", "`n" ShowSchemalistbox_left "`n"){
					IsChange++
					GuiControl,schema:,ShowSchemalistbox_right,% ShowSchemalistbox_left
				}
			}
		case "ShowSchemalistbox_right":
			Gui,schema:Submit,NoHide
			if (A_GuiEvent="doubleClick"){
				IsChange++
				ControlGet, Schemalistbox2, List , , listBox2, ahk_id %SelectSchemaList%
				GuiControl,schema:,ShowSchemalistbox_right,% RegExReplace(StrReplace("`n" Trim(Schemalistbox2,"`n"),"`n" ShowSchemalistbox_right),"`n","|")
			}
		}
Return

schemaGuiClose:
	if IsChange {
		ControlGet, Schemalistbox2, List , , listBox2, ahk_id %SelectSchemaList%
		if Schemalistbox2 {
			Submit_Default["schema_list"]:=[]
			Loop,Parse,Schemalistbox2,`n,`r
			{
				if schemaObject[Trim(A_LoopField)]
					Submit_Default["schema_list"].Push(schemaObject[Trim(A_LoopField)])
			}
			Gosub Control_Weasel_last
			DefaultYaml_Config:=MatchWeaselItems.GetDefaultYaml()
		}
	}
	Gui,schema:Destroy
Return

GetRimeSchemalist(){
	Global RimeUserDir,WeaselRoot,schemaObject,FileLists,schemaIdObject
	Static schema_list
	schema_list:="",schemaObject:={},FileLists:={},schemaIdObject:={}
	if FileExist(RimeUserDir "\*.schema.yaml"){
		Loop,Files,%RimeUserDir%\*.schema.yaml
		{
			if objCount(obj:=yaml(A_LoopFileFullPath,1,"utf-8")){
				if FileExist(RimeUserDir "\" Trim(obj["translator","dictionary"]) (".dict.yaml")){
					schemaIdObject[Trim(obj["schema","schema_id"])]:=Trim(obj["schema","name"])
					schemaObject[Trim(obj["schema","name"])]:=Trim(obj["schema","schema_id"]),schema_list.="|" Trim(obj["schema","name"])
					FileLists[Trim(obj["schema","name"])]:=RimeUserDir "\" Trim(obj["translator","dictionary"]) ".dict.yaml"
				}
			}
		}
	}
	if FileExist(WeaselRoot "\data\*.schema.yaml"){
		Loop,Files,%WeaselRoot%\data\*.schema.yaml
		{
			if objCount(obj:=yaml(A_LoopFileFullPath,1,"utf-8")){
				if !schemaIdObject[Trim(obj["schema","schema_id"])]&&FileExist(WeaselRoot "\data\" Trim(obj["translator","dictionary"]) (".dict.yaml")){
					schemaIdObject[Trim(obj["schema","schema_id"])]:=Trim(obj["schema","name"])
					schemaObject[Trim(obj["schema","name"])]:=Trim(obj["schema","schema_id"]),schema_list.="|" Trim(obj["schema","name"])
					FileLists[Trim(obj["schema","name"])]:=WeaselRoot "\data\" Trim(obj["translator","dictionary"]) ".dict.yaml"
				}
			}
		}
	}
	Return Trim(schema_list,"|")
}

options_color_scheme:
	default_preset_color:={color_scheme:"steam" 
		,name: "Steam"
		,author: "Patricivs <ipatrickmac@me.com>"
		,back_color: 0x141617
		,border_color: 0x353638
		,text_color: 0xcd8c52
		,hilited_text_color: 0xc9cfd1
		,hilited_back_color: 0x141617
		,hilited_candidate_back_color: 0x594231
		,hilited_candidate_text_color: 0xffffff
		,hilited_comment_text_color: 0xa7a7a9
		,hilited_label_color: 0xffffff
		,hilited_candidate_label_color: 0xffffff
		,candidate_text_color: 0xffffff
		,comment_text_color: 0xa7a7a9
		,label_color: 0xffffff}
	WeaselYaml_Config:=MatchWeaselItems.GetWeaselYaml()
	Gui,ColorTheme:Destroy
	Gui,ColorTheme:Default
	OwnerGui:=WinExist("ahk_id " weaselGui)?" +OwnerWeasel ":""
	IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	DefaultFontName:=GetDefaultFontName()
	Gui,ColorTheme: -MaximizeBox %OwnerGui% -DPIScale  HWNDSetColorTheme
	Gui,ColorTheme:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,ColorTheme:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme:Add,GroupBox,vGrBox5 w500 Center,配色预览
	Gui,ColorTheme:Add,GroupBox, vGrBox6 w500 Center,Yaml代码
	Gui,ColorTheme:Add,GroupBox,x+20 ym vGrBox1,背景边框色

	GuiControlGet,GrBoxpos1,ColorTheme:Pos,GrBox1
	Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y" GrBoxpos1Y+40,背景:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vback_color w135 HWNDSet_back_color,0xffffff
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,边框:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vborder_color w135,0xffffff
	GuiControlGet,bgpos,ColorTheme:Pos,back_color
	GuiControl,ColorTheme:Move,GrBox1, % "h" bgposH*2+75 " w" bgposW*1.7

	GuiControlGet,GrBoxpos1,ColorTheme:Pos,GrBox1
	Gui,ColorTheme:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme:Add,GroupBox,% "x" GrBoxpos1X " y" GrBoxpos1Y+GrBoxpos1H+5 " w" GrBoxpos1W " h" bgposH*4+100 " vGrBox2",内选编码区域
	Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " yp+40",文字:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme vtext_color  w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,编码:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_text_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,背景:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_back_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,标签:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_label_color w135,0XFFFFFF

	GuiControlGet,GrBoxpos2,ColorTheme:Pos,GrBox2
	Gui,ColorTheme:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme:Add,GroupBox,% "x" GrBoxpos1X " y" GrBoxpos2Y+GrBoxpos2H+5 " w" GrBoxpos1W " h" GrBoxpos2H " vGrBox3",候选激活区域
	Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " yp+40",文字:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_candidate_text_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,背景:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_candidate_back_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,注解:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_comment_text_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,标签:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vhilited_candidate_label_color w135,0XFFFFFF

	GuiControlGet,GrBoxpos3,ColorTheme:Pos,GrBox3
	Gui,ColorTheme:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme:Add,GroupBox,% "x" GrBoxpos1X " y" GrBoxpos3Y+GrBoxpos3H+5 " w" GrBoxpos2W " h" GrBoxpos2H-bgposH " vGrBox4",候选其它区域
	Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " yp+40",文字:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vcandidate_text_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,注解:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vcomment_text_color w135,0XFFFFFF
	Gui,ColorTheme: Add, text,% " BackgroundTrans x" GrBoxpos1X+15 " y+15" ,标签:
	Gui,ColorTheme:Add,Button,x+10 yp-2 gControl_Theme  vlabel_color w135,0xffffff

	GuiControl,ColorTheme:Move,GrBox5, % "h" GrBoxpos2H+GrBoxpos1H 
	GuiControl,ColorTheme:Move,GrBox6, % "h" GrBoxpos2H*2-bgposH " y+" GrBoxpos2H+GrBoxpos1H+20
	GuiControlGet,GrBoxpos5,ColorTheme:Pos,GrBox5
	GuiControlGet,GrBoxpos6,ColorTheme:Pos,GrBox6
	Gui,ColorTheme:Font,% "s9 norm " (!IsLightTheme?"cF4C51F":"c57A4A1"),% DefaultFontName

	if sciIsload {
		Sci := New Scintilla(SetColorTheme, GrBoxpos6X+20, GrBoxpos6Y+30, GrBoxpos6W-40,GrBoxpos6H-50, 0x50000000, 0x200)
		,Sci.StyleSetBack(STYLE_DEFAULT, !IsLightTheme?0x333333:0xeefeff)   ;前景色绘制
		,Sci.StyleSetFore(STYLE_DEFAULT, !IsLightTheme?0xf0f0f0:0x333333)   ;显示字体颜色
		,Sci.SetCodePage(65001)
		,Sci.SetWrapMode(True)  ;自动换行对齐显示  SC_WRAP_WORD:= 3
		,SCI.SETUSETABS(True)   ;False:以空格代替tab,反之
		,SCI.SETINDENT(False)  ;根据STYLE_DEFAULT中的空格宽度设置缩进大小。如果将宽度设置为0，则缩进大小与制表符大小相同。缩进大小没有限制，但是小于0的值或较大的值可能会产生不良影响
		,sci.SetModEventMask(SC_MOD_INSERTTEXT|SC_MOD_DELETETEXT)
		,Sci.SetMarginWidthN(0, 0)
		,Sci.SetMarginMaskN(1, SC_MASK_FOLDERS)
		,sci.SetWrapVisualFlags(1|2)
		,Sci.SetMarginSensitiveN(1, true)
		,Sci.SetMarginLeft(0, 5)
		,Sci.SetMarginWidthN(1, 0)
		,SCI.SETWRAPSTARTINDENT(5) ; \/
		,Sci.AUTOCSETSEPARATOR(10)
		,sci.SETCARETWIDTH(2)
		,Sci.SetCaretLineBack(0x40FF40)
		,Sci.SetCaretLineVisible(True)
		,Sci.SetCaretLineVisibleAlways(1)
		,Sci.GoToPos(1)
		,Sci.SetViewEOL(0)
		,Sci.2086(4)
		,Sci.SetWhiteSpaceFore(1, 0xd77800)
		,Sci.SetViewWS(1)
		,SCI.CONVERTEOLS(0)
	}Else{
		Gui,ColorTheme:Add,Edit,%  "x" GrBoxpos6X+20 " y" GrBoxpos6Y+30 " w" GrBoxpos6W-40 " h" GrBoxpos6H-50 " -Border +ReadOnly -WantReturn -WantCtrlA -Wrap -E0x200 gControl_Theme vThemeArea HWNDThemeEditArea",
	}

	For key,value In default_preset_color
	{
		if value~="i)^(0x[a-fA-F]+|\d+)$"{
			SetButtonColor(key,FormatColor_BGR(format("0x{:06X}",value)),"ColorTheme")
			GuiControl,ColorTheme:,%key%,% format("0x{:06X}",value)
		}
	}
	Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	GuiControlGet,GrBoxpos5,ColorTheme:Pos,GrBox5
	PicWidth:=GrBoxpos5W*0.35,PicHeight:=GrBoxpos5H-50
	Gui,ColorTheme: Add, Pic,% "x" GrBoxpos5X+15 " y" GrBoxpos5Y+30 " w" PicWidth " h" GrBoxpos2H+GrBoxpos1H-50 " vborder_color_pic", % "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight, FormatColor_BGR(default_preset_color["border_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["border_color"]):"0x000000"))
	Gui,ColorTheme: Add, Pic,% "xp+8 yp+8 w" PicWidth-16 " h" PicHeight-16 " vback_color_pic", % "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,  FormatColor_BGR(default_preset_color["back_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["back_color"]):"0x000000"))

	Gui,ColorTheme: Add, Text,% "xp+8 yp+8 BackgroundTrans vtext_color_pic c" SubStr(FormatColor_BGR(default_preset_color["text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["text_color"]):"0x000000"),3), 小狼毫
	Gui,ColorTheme: Add, Pic,% "x+8 yp w" PicWidth-16 " h" PicHeight-16 " vhilited_back_color_pic ", % "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,  FormatColor_BGR(default_preset_color["hilited_back_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_back_color"]):"0x000000"))
	Gui,ColorTheme: Add, Text,% "xp+4 yp BackgroundTrans vhilited_text_color_pic c" SubStr(FormatColor_BGR(default_preset_color["hilited_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_text_color"]):"0x000000"),3), pei'se
	GuiControlGet,ttcppos,ColorTheme:Pos,hilited_text_color_pic
	GuiControl,ColorTheme:Move,hilited_back_color_pic,% "w" ttcpposW+8 " h" ttcpposH+4
	GuiControl,ColorTheme:, hilited_back_color_pic,% "HBITMAP:" . CreateColoredBitmap(ttcpposW+12,  ttcpposH+8,FormatColor_BGR(default_preset_color["hilited_back_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_back_color"]):"0x000000"))

	GuiControlGet,BCPos,ColorTheme:Pos,back_color_pic
	GuiControlGet,HTCPos,ColorTheme:Pos,hilited_text_color_pic
	Gui,ColorTheme: Add, Pic,% "x" BCPosX+8 " y+25 w" BCPosW-16 " h" HTCPosH+10 " vhilited_candidate_back_color_pic", % "HBITMAP:" . CreateColoredBitmap(BCPosW-16, HTCPosH+10, FormatColor_BGR(default_preset_color["hilited_candidate_back_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_candidate_back_color"]):"0x000000"))
	;;Gui,ColorTheme: Add, Text,% "xp+4 yp+5 BackgroundTrans vhilited_candidate_label_color_pic c" SubStr(FormatColor_BGR(default_preset_color["hilited_candidate_label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_candidate_label_color"]?default_preset_color["hilited_candidate_label_color"]:default_preset_color["hilited_candidate_text_color"]):?:default_preset_color["hilited_candidate_text_color"]),3), 1.
	Gui,ColorTheme: Add, Text,% "xp+4 yp+5 BackgroundTrans vhilited_label_color_pic c" SubStr(FormatColor_BGR(default_preset_color["hilited_label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_label_color"]?default_preset_color["hilited_label_color"]:default_preset_color["hilited_candidate_text_color"]):?:default_preset_color["hilited_candidate_text_color"]),3), 1.
	Gui,ColorTheme: Add, Text,% "x+4 yp BackgroundTrans vhilited_candidate_text_color_pic1 c" SubStr(FormatColor_BGR(default_preset_color["hilited_candidate_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_candidate_text_color"]):"0x000000"),3), 配色
	Gui,ColorTheme: Add, Text,% "x+25 yp BackgroundTrans vhilited_comment_text_color_pic c" SubStr(FormatColor_BGR(default_preset_color["hilited_comment_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["hilited_comment_text_color"]):default_preset_color["hilited_candidate_text_color"]<>""?default_preset_color["hilited_candidate_text_color"]"0x000000"),3),sgqc

	;;GuiControlGet,HCLCPos,ColorTheme:Pos,hilited_candidate_label_color_pic
	GuiControlGet,HCLCPos,ColorTheme:Pos,hilited_label_color_pic
	GuiControlGet,HCTCPos,ColorTheme:Pos,hilited_candidate_text_color_pic1
	Gui,ColorTheme: Add, Text,% "x" HCLCPosX " y+22 BackgroundTrans vlabel_color_pic1 c" SubStr(FormatColor_BGR(default_preset_color["label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["label_color"]):"0x000000"),3), 2.
	GuiControlGet,LCPos,ColorTheme:Pos,label_color_pic1
	Gui,ColorTheme: Add, Text,% "x+4 w" HCTCPosW " yp BackgroundTrans vcandidate_text_color_pic1 c" SubStr(FormatColor_BGR(default_preset_color["candidate_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["candidate_text_color"]):"0x000000"),3), 陪
	Gui,ColorTheme: Add, Text,% "x+25 yp BackgroundTrans vcomment_text_color_pic1 c" SubStr(FormatColor_BGR(default_preset_color["comment_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["comment_text_color"]):"0x000000"),3), bukg

	Gui,ColorTheme: Add, Text,% "x" HCLCPosX " y+22 BackgroundTrans vlabel_color_pic2 c" SubStr(FormatColor_BGR(default_preset_color["label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["label_color"]):"0x000000"),3), 3.
	Gui,ColorTheme: Add, Text,% "x+4 w" HCTCPosW " yp BackgroundTrans vcandidate_text_color_pic2 c" SubStr(FormatColor_BGR(default_preset_color["candidate_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["candidate_text_color"]):"0x000000"),3), 配
	Gui,ColorTheme: Add, Text,% "x+25 yp BackgroundTrans vcomment_text_color_pic2 c" SubStr(FormatColor_BGR(default_preset_color["comment_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["comment_text_color"]):"0x000000"),3), sgnn

	Gui,ColorTheme: Add, Text,% "x" HCLCPosX " y+22 BackgroundTrans vlabel_color_pic3 c" SubStr(FormatColor_BGR(default_preset_color["label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["label_color"]):"0x000000"),3), 4.
	Gui,ColorTheme: Add, Text,% "x+4 w" HCTCPosW " yp BackgroundTrans vcandidate_text_color_pic3 c" SubStr(FormatColor_BGR(default_preset_color["candidate_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["candidate_text_color"]):"0x000000"),3), 赔
	Gui,ColorTheme: Add, Text,% "x+25 yp BackgroundTrans vcomment_text_color_pic3 c" SubStr(FormatColor_BGR(default_preset_color["comment_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["comment_text_color"]):"0x000000"),3), mukg

	Gui,ColorTheme: Add, Text,% "x" HCLCPosX " y+22 BackgroundTrans vlabel_color_pic4 c" SubStr(FormatColor_BGR(default_preset_color["label_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["label_color"]):"0x000000"),3), 5.
	Gui,ColorTheme: Add, Text,% "x+4 w" HCTCPosW " yp BackgroundTrans vcandidate_text_color_pic4 c" SubStr(FormatColor_BGR(default_preset_color["candidate_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["candidate_text_color"]):"0x000000"),3), 培
	Gui,ColorTheme: Add, Text,% "x+25 yp BackgroundTrans vcomment_text_color_pic4 c" SubStr(FormatColor_BGR(default_preset_color["comment_text_color"]~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",default_preset_color["comment_text_color"]):"0x000000"),3), fukg

	Gui,ColorTheme:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"c333333"),% DefaultFontName
	Gui,ColorTheme: Add, Text,% "x" BCPosX+BCPosW+20 " y" BCPosY " vTextInfo2",主题ID：
	GuiControlGet,TPos,ColorTheme:Pos,TextInfo2
	Gui,ColorTheme: Add, Edit,% "x+0 yp+2 r1 w" GrBoxpos5W-BCPosW-TPosW*2.2 " gControl_Theme vcolor_scheme_1 Lowercase",% default_preset_color["color_scheme"]
	Gui,ColorTheme: Add, Text,% "x" BCPosX+BCPosW+20 " y+15 Center w" TPosW,名称：
	Gui,ColorTheme: Add, Edit,% "x+0 yp+2 r1 w" GrBoxpos5W-BCPosW-TPosW*2.2 " gControl_Theme vname ",% default_preset_color["name"]
	Gui,ColorTheme: Add, Text,% "x" BCPosX+BCPosW+20 " y+15 Center w" TPosW,作者：
	Gui,ColorTheme: Add, Edit,% "x+0 yp+2 r3 w" GrBoxpos5W-BCPosW-TPosW*2.2 " gControl_Theme vauthor ",% default_preset_color["author"]
	Gui,ColorTheme: Add, Text,% "x" BCPosX+BCPosW+20 " y+15 Center w" TPosW,列表：
	Gui,ColorTheme: Add, ddl,% "x+0 yp+2 w" GrBoxpos5W-BCPosW-TPosW*2.2 " gControl_Theme vColorThemeList",
	Gui,ColorTheme: Add, Checkbox,% "x" BCPosX+BCPosW+100 " y+20 gControl_Theme vGetColorType " (!Select_Color_Type?"c00B7FD":"ce81010") " Checked ",% Select_Color_Type?"自由取色":"选色面板"
	Gui,ColorTheme: Add, Button,% "x" BCPosX+BCPosW+40 " y+20 gControl_Theme vCopyTheme_1",复制配置
	Gui,ColorTheme: Add, Button,x+30 yp gControl_Theme vSaveTheme Disabled,写入配置
	Gui,ColorTheme: Show,NA AutoSize,% A_IsAdmin?"[管理员] 小狼毫配色辅助":"小狼毫配色辅助"
	GuiControl,ColorTheme:,ColorThemeList, % GetThemeList(WeaselYaml_Config["preset_color_schemes"])
	GuiControl,ColorTheme:ChooseString,ColorThemeList,% default_preset_color["color_scheme"]
	WinActivate,ahk_id %SetColorTheme%
	ControlFocus,ThemeArea,ahk_id %SetColorTheme%
	if sciIsload {
		Sci.SetText("" , format_default_preset_color(default_preset_color), 1),Sci.GoToPos(1)
		Sci.StyleSetBack(STYLE_DEFAULT, !IsLightTheme?0x333333:0xeefeff)   ;前景色绘制
		Sci.StyleSetFore(STYLE_DEFAULT, !IsLightTheme?0xf0f0f0:0x333333)   ;显示字体颜色
		Sci.StyleSetFont(STYLE_DEFAULT, DefaultFontName,2)   ;字体
		Sci.StyleSetSize(STYLE_DEFAULT, 9)   ;字号
		Sci.StyleClearAll()
		Sci.SetMouseDwellTime(1000)

		sci.StyleSetSize(SCE_AHKL_USERDEFINED3, 10)
		sci.StyleSetBold(SCE_AHKL_USERDEFINED3, true)
		sci.StyleSetFore(SCE_AHKL_USERDEFINED3, 0x0)
		Sci.StyleSetBack(SCE_AHKL_USERDEFINED3, 0xeefeff)

		Sci.StyleSetFore(STYLE_BRACELIGHT, 0x000000)
		Sci.StyleSetBack(STYLE_BRACELIGHT, 0xFFFF00)
		Sci.StyleSetBold(STYLE_BRACELIGHT, True)
		Sci.StyleSetFore(STYLE_BRACEBAD, 0xFF0000)
		SCI.SETREADONLY(1)
	}Else
		GuiControl,ColorTheme:,ThemeArea,% format_default_preset_color(default_preset_color)
Return

ColorThemeGuiClose:
	Gui,ColorTheme:Destroy
	Gosub Select_Color_func
	EmptyMem()
Return

EditGetSel(hCtl, ByRef vPos1, ByRef vPos2)
{
	VarSetCapacity(vPos1, 4), VarSetCapacity(vPos2, 4)
	SendMessage, 0xB0, % &vPos1, % &vPos2,, % "ahk_id " hCtl ;EM_GETSEL := 0xB0 ;(left, right)
	vPos1 := NumGet(&vPos1, 0, "UInt"), vPos2 := NumGet(&vPos2, 0, "UInt")
}

EditSetSel(hWnd, vPos1, vPos2, vDoScroll:=0)
{
	static EM_SETSEL := 0xB1
	static EM_SCROLLCARET := 0xB7
	SendMessage, EM_SETSEL, %vPos1%, %vPos2%,, ahk_id %hWnd%  ;EM_SETSEL := 0xB1 ;(anchor, active)
	if vDoScroll
		SendMessage, EM_SCROLLCARET, 0, 0,, ahk_id %hWnd%  ;EM_SCROLLCARET := 0xB7
}

Control_Theme:
	GuiControlGet,ControlGetVar,,%A_GuiControl%,Text
	Switch A_GuiControl
	{
		Case "color_scheme_1":
			Gui,ColorTheme:Submit,NoHide
			if color_scheme_1~="[^\w]"{
				GuiControl,ColorTheme:,color_scheme_1,% color_scheme_1:=RegExReplace(color_scheme_1,"[^\w]")
				Send,{End}
				Gui,+OwnDialogs
				MsgBox,262192,错误警告,主题名称不支持中文！请输入字母与下划线组合。
			}
			if sciIsload {
				HighlightIdenticalText(""),Sci.SetCaretLineBack(0xeefeff),Sci.SETREADONLY(0)
				RegExMatch(GetTextRange([0,sci.GetLength()]),"i)^(\s*\w*\:)",match)
				if !objCount(HighlightIdenticalPos:=HighlightIdenticalText(match)){
					Sci.InsertText(0, A_Space . A_Space . Trim(%A_GuiControl%) ":`r`n", 1)
					HighlightIdenticalPos:=HighlightIdenticalText(A_Space . A_Space . Trim(%A_GuiControl%) ":`r`n"),Sci.SETREADONLY(1)
				}Else{
					for Section,element In HighlightIdenticalPos
					{
						Sci.SetSel(element[1],element[1]+element[2])
						ReplaceText:=A_Space . A_Space . Trim(%A_GuiControl%) ":"
						SetSelectedText(ReplaceText)
					}
				}
				Sci.SetCaretLineBack(0x40FF40),Sci.SETREADONLY(1)
			}Else
				GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"^(" A_Space "+\w+\:)","  " color_scheme_1 ":")
			Process,Exist,WeaselServer.exe
			if ErrorLevel
				GuiControl,ColorTheme:Enable,SaveTheme
		Case "name":
			Gui,ColorTheme:Submit,NoHide
			name:=RegExReplace(name,"[\r\n\t]")
			if name {
				if sciIsload {
					HighlightIdenticalText(""),Sci.SetCaretLineBack(0xeefeff),Sci.SETREADONLY(0)
					RegExMatch(GetTextRange([0,sci.GetLength()]),"i)(\s" A_GuiControl "\:\s[^\r\n]+)",match)
					if !objCount(HighlightIdenticalPos:=HighlightIdenticalText(match)){
						Sci.InsertText(sci.GetLineEndPosition(sci.GetLineCount()+1), "`r`n    " . A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """", 1)
						HighlightIdenticalPos:=HighlightIdenticalText(A_Space A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """"),Sci.SETREADONLY(1)
					}Else{
						for Section,element In HighlightIdenticalPos
						{
							Sci.SetSel(element[1],element[1]+element[2])
							ReplaceText:=A_Space A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """"
							SetSelectedText(ReplaceText)
						}
					}
					Sci.SetCaretLineBack(0x40FF40),Sci.SETREADONLY(1)
				}Else
					GuiControl,ColorTheme:,ThemeArea,% InStr(Trim(ThemeArea,"`r`n")," name:" )?RegExReplace(Trim(ThemeArea,"`r`n"),"i)(?<=\sname\:)[^\r\n]+",A_Space """" Trim(name) """"):Trim(ThemeArea,"`r`n") "`r`n    name:" A_Space """" Trim(name) """"
				Process,Exist,WeaselServer.exe
				if ErrorLevel
					GuiControl,ColorTheme:Enable,SaveTheme
			}
		Case "author":
			Gui,ColorTheme:Submit,NoHide
			author:=RegExReplace(author,"[\r\n\t]")
			;if author {
				if sciIsload {
					HighlightIdenticalText(""),Sci.SetCaretLineBack(0xeefeff),Sci.SETREADONLY(0)
					RegExMatch(GetTextRange([0,sci.GetLength()]),"i)(\s" A_GuiControl "\:\s[^\r\n]+)",match)
					if !objCount(HighlightIdenticalPos:=HighlightIdenticalText(match)){
						Sci.InsertText(sci.GetLineEndPosition(sci.GetLineCount()+1), "`r`n    " . A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """", 1)
						HighlightIdenticalPos:=HighlightIdenticalText(A_Space A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """"),Sci.SETREADONLY(1)
					}Else{
						for Section,element In HighlightIdenticalPos
						{
							Sci.SetSel(element[1],element[1]+element[2])
							ReplaceText:=A_Space A_GuiControl ":" A_Space """" Trim(%A_GuiControl%) """"
							SetSelectedText(ReplaceText)
						}
					}
					Sci.SetCaretLineBack(0x40FF40),Sci.SETREADONLY(1)
				}Else
					GuiControl,ColorTheme:,ThemeArea,% InStr(Trim(ThemeArea,"`r`n")," author:" )?RegExReplace(Trim(ThemeArea,"`r`n"),"i)(?<=\sauthor\:)[^\r\n]+",A_Space """" Trim(author) """"):Trim(ThemeArea,"`r`n") "`r`n    author:" A_Space """" Trim(author) """"
				Process,Exist,WeaselServer.exe
				if ErrorLevel
					GuiControl,ColorTheme:Enable,SaveTheme
			;}
		Case "ColorThemeList":
			GuiControl,ColorTheme:Disable,SaveTheme
			Gui,ColorTheme:Submit,NoHide
			if objCount(ColorObj:=WeaselYaml_Config["preset_color_schemes",ThemeList[ControlGetVar]]) {
				ColorObj["color_scheme"]:=ThemeList[ControlGetVar]
				if sciIsload
					Sci.SETREADONLY(0),Sci.SetText("" , format_default_preset_color(ColorObj), 1),SCI.SETREADONLY(1),Sci.GoToPos(1)
				Else
					GuiControl,ColorTheme:,ThemeArea,% format_default_preset_color(ColorObj)
				GuiControl,ColorTheme:,color_scheme_1,% ThemeList[ControlGetVar]
				for Section,element In default_preset_color
				{
					Switch Section
					{
						case "text_color":
							ColorObj[Section]:=ColorObj[Section]<>""?ColorObj[Section]:ColorObj["candidate_text_color"]<>""?ColorObj["candidate_text_color"]:0xffffff
						case "candidate_text_color":
							ColorObj[Section]:=ColorObj[Section]<>""?ColorObj[Section]:ColorObj["text_color"]<>""?ColorObj["text_color"]:0xffffff
						case "hilited_comment_text_color":
							ColorObj[Section]:=ColorObj[Section]?ColorObj[Section]:ColorObj["hilited_candidate_text_color"]
						case "comment_text_color":
							ColorObj[Section]:=ColorObj[Section]?ColorObj[Section]:ColorObj["candidate_text_color"]
						case "hilited_label_color":
							ColorObj[Section]:=ColorObj[Section]?ColorObj[Section]:ColorObj["hilited_candidate_text_color"]
						case "label_color":
							ColorObj[Section]:=ColorObj[Section]?ColorObj[Section]:ColorObj["candidate_text_color"]
						case "hilited_candidate_label_color":
							ColorObj[Section]:=ColorObj[Section]?ColorObj[Section]:ColorObj["hilited_candidate_text_color"]
					}
					change_button_color(Section,ColorObj[Section])
				}
			}
		case "CopyTheme_1":
			Gui,ColorTheme:Submit,NoHide
			if sciIsload
				ThemeArea:=GetTextRange([0,sci.GetLength()])
			Clipboard:=RegExReplace(Trim(ThemeArea,"`r`n"),"^(\s+)(\w+)(\:)","  " """" "preset_color_schemes/$2" """" "$3")
			ClipWait,0
			if (ThemeArea&&InStr(Clipboard,Trim(color_scheme_1)))
				TrayTip,小狼毫助手,配色已复制至剪切板！,,1
		case "SaveTheme":
			IsChangeTheme:=0
			Gui,ColorTheme:Submit,NoHide
			if sciIsload
				ThemeArea:=GetTextRange([0,sci.GetLength()])
			Gui,+OwnDialogs
			MsgBox,262179,写入确认,点击「是」—>保存并应用该主题；`n点击「否」—>仅保存该主题配色；`n点击「取消」—>取消操作。
			IfMsgBox,Cancel
			{
				Return
			}
			Else IfMsgBox,Yes
			{
				IsChangeTheme:=!IsChangeTheme
			}
			if (Trim(name)&&Trim(color_scheme_1)){
				if !ThemeList[Trim(name)]&&!objCount(WeaselYaml_Config["preset_color_schemes",Trim(color_scheme_1)]){
					Content:=FileExist(RimeUserDir "\weasel.custom.yaml")?MatchWeaselItems.GetFileContent(RimeUserDir "\weasel.custom.yaml","UTF-8",1):"patch`r`n"
					if Content~="preset_color_schemes\/" Trim(color_scheme_1) "[\""""\:]"{
						Gui,+OwnDialogs
						MsgBox,262160,Error,主题配色已存在，请手动删除！
					}else{
						all:=RegExReplace(Trim(ThemeArea,"`r`n"),"^(\s+)(\w+)(\:)","  " """" "preset_color_schemes/$2" """" "$3")
						if (all<>Trim(ThemeArea,"`r`n")){
							ThemeList[Trim(name)]:=Trim(color_scheme_1)
							GuiControl,ColorTheme:,ColorThemeList,% Trim(name)
							if WinExist("ahk_id " weaselGui)
								GuiControl,Weasel:,change_theme,% Trim(name)
							for key,value In default_preset_color
							{
								GuiControlGet,item,,%key%,Text
								if (key<>"color_scheme")
									WeaselYaml_Config["preset_color_schemes",Trim(color_scheme_1),key]:=item?item:"0x000000"
							}
							Content:=RegExReplace(Content,"i)(patch\:\r\n)","$1" all "`r`n`r`n")
							FileDelete,%RimeUserDir%\weasel.custom.yaml
							FileAppend,% MatchWeaselItems.FormatYaml(Content),%RimeUserDir%\weasel.custom.yaml,UTF-8
							if IsChangeTheme
								MatchWeaselItems.ModifyWeaselYaml({"style/color_scheme":Trim(color_scheme_1)})
							TrayTip,小狼毫助手,当前配色已添加，正在部署请稍候！,,1
							GuiControl,ColorTheme:Disable,SaveTheme
							MatchWeaselItems.DeployWeasel()
						}
					}
				}Else{
					Content:=FileExist(RimeUserDir "\weasel.custom.yaml")?MatchWeaselItems.GetFileContent(RimeUserDir "\weasel.custom.yaml","UTF-8",1):"patch`r`n"
					if Content~="[\""""]*preset_color_schemes\/" Trim(color_scheme_1) "[\""""]*\:"{
						all:=RegExReplace(Trim(ThemeArea,"`r`n"),"^(\s+)(\w+)(\:)","  " """" "preset_color_schemes/$2" """" "$3")
						Content2:=RegExReplace(Content,"i)\s+[\""""]*preset_color_schemes\/" Trim(color_scheme_1) "[\""""]*\:\s*([\r\n]+\s*(name|author|back_color|border_color|candidate_text_color|comment_text_color|hilited_back_color|hilited_candidate_label_color|hilited_label_color|hilited_candidate_back_color|hilited_candidate_text_color|hilited_comment_text_color|hilited_text_color|label_color|text_color)\:\s+[^\r\n]+)+|\s+[\""""]*preset_color_schemes\/" Trim(color_scheme_1) "[\""""]*\:\s+\{[^\r\n]+\}")
						if (Content2<>Content){
							for key,value In default_preset_color
							{
								GuiControlGet,item,,%key%,Text
								if (key<>"color_scheme")
									WeaselYaml_Config["preset_color_schemes",Trim(color_scheme_1),key]:=item?item:"0x000000"
							}
							Content:=RegExReplace(RegExReplace(Content2,"(*BSR_ANYCRLF)\R+", "`r`n"),"i)(patch\:\r\n)","$1" all "`r`n`r`n")
							FileDelete,%RimeUserDir%\weasel.custom.yaml
							FileAppend,% MatchWeaselItems.FormatYaml(Content),%RimeUserDir%\weasel.custom.yaml,UTF-8
							if IsChangeTheme
								MatchWeaselItems.ModifyWeaselYaml({"style/color_scheme":Trim(color_scheme_1)})
							TrayTip,小狼毫助手,用户同名主题已修改，正在部署请稍候！,,1
							GuiControl,ColorTheme:Disable,SaveTheme
							MatchWeaselItems.DeployWeasel()
						}Else{
							Gui,+OwnDialogs
							MsgBox,262160,Error,用户同名主题修改失败！
						}
					}Else{
						Gui,+OwnDialogs
						MsgBox,262160,Error,自带主题中已存在同名主题！
					}
				}
			}Else{
				Gui,+OwnDialogs
				MsgBox,262160,Error,主题名称和主题ID栏不能为空！
			}
		case "GetColorType":
			Gui,ColorTheme:Submit,NoHide
			Select_Color_Type:=!Select_Color_Type
			GuiControl,ColorTheme:,GetColorType,% Select_Color_Type?"自由取色":"选色面板"
			Gui,ColorTheme:Font,% "s9 norm " (!Select_Color_Type?"c00B7FD":"ce81010"),% DefaultFontName
			GuiControl,ColorTheme:Font,GetColorType
			GuiControl,ColorTheme:,GetColorType,1
		case "back_color","border_color","text_color","hilited_text_color","hilited_back_color","hilited_candidate_back_color","hilited_candidate_text_color","hilited_comment_text_color","candidate_text_color","comment_text_color","label_color","hilited_candidate_label_color","hilited_label_color":
			Gui,ColorTheme:Submit,NoHide
			if sciIsload {
				HighlightIdenticalText(""),Sci.SetCaretLineBack(0x1010e8),Sci.SETREADONLY(0)
				GuiControlGet,BtnText,,%A_GuiControl%,Text
				if !objCount(HighlightIdenticalPos:=HighlightIdenticalText(A_Space A_GuiControl ": " BtnText)){
					Sci.InsertText(sci.GetLineEndPosition(sci.GetLineCount()+1), "`r`n    " . A_GuiControl ": 0x000000", 1)
					HighlightIdenticalPos:=HighlightIdenticalText(A_Space A_GuiControl ": 0x000000")
				}
			}Else{
				if !InStr(Trim(ThemeArea,"`r`n"),A_Space A_GuiControl ":")
					GuiControl,ColorTheme:,ThemeArea,% Trim(ThemeArea,"`r`n") "`r`n    " A_GuiControl ": 0x000000"
			}
			Select_Color_Mode:=1,button_label:=A_GuiControl,btt("",,,2),btt("",,,1)
			if Select_Color_Type {
				Hotkey,$LCtrl,Select_Process_func,Off
				Hotkey,$LCtrl,Select_Color_func,On
				SetTimer, Watch_Select_Color, 100
			}Else{
				Hotkey,$LCtrl,Select_Process_func,Off
				Gosub Select_Color_func
				if sciIsload {
					HighlightIdenticalText(""),Sci.SetCaretLineBack(0x1010e8),Sci.SETREADONLY(0),Sci.SetSel(HighlightIdenticalPos[1,1],HighlightIdenticalPos[1,1]+HighlightIdenticalPos[1,2])
				}
				If Dlg_Color(tempColor, SetColorTheme){
					change_button_color(A_GuiControl,FormatColor_BGR(tempColor))
					if sciIsload {
						for Section,element In HighlightIdenticalPos
						{
							Sci.SetSel(element[1],element[1]+element[2])
							ReplaceText:=A_Space A_GuiControl ": " FormatColor_BGR(tempColor)
							SetSelectedText(ReplaceText)
						}
						Sci.SetCaretLineBack(0x40FF40),Sci.SETREADONLY(1)
					}
				}
			}
			Process,Exist,WeaselServer.exe
			if ErrorLevel
				GuiControl,ColorTheme:Enable,SaveTheme
	}
Return

HighlightIdenticalText(String="") {
	Global Sci
	Position:=[]
	if String {
		SelEnd := Sci.GetSelectionEnd()
		Sci.SetIndicatorCurrent(2)
		Sci.IndicSetStyle(2, 8) ; INDIC_STRAIGHTBOX
		Sci.IndicSetFore(2, 0xce7539)
		Sci.IndicSetOutlineAlpha(2, 80) ; Opaque border
		Sci.IndicSetAlpha(2, 100)

		TextLength := Sci.GetLength()
		Sci.SetTargetStart(0)
		Sci.SetTargetEnd(TextLength)
		StringLength := StrPut(String, "UTF-8") - 1
/*
SCFIND_MATCHCASE	仅与匹配搜索字符串大小写的文本匹配。
SCFIND_WHOLEWORD	仅当前后的字符不是单词字符时，才会发生匹配。
SCFIND_WORDSTART	仅当前面的字符不是单词字符时，才会发生匹配。
SCFIND_REGEXP	搜索字符串应解释为正则表达式。
.	匹配任何字符
\(	这标志着标记比赛的区域的开始。
\)	这标志着标记区域的结束。
\n	其中n1到9表示替换时第一个到第九个标记的区域。例如，如果搜索字符串为Fred\([1-9]\)XXX，替换字符串为Sam\1YYY，Fred2XXX则将其应用于时会生成Sam2YYY。
\<	使用Scintilla的单词定义来匹配单词的开头。
\>	使用Scintilla的单词定义可以匹配单词的结尾。
\x	这使您可以使用字符x，否则该字符x会具有特殊含义。例如，\ [将被解释为[，而不是字符集的开头。
[...]	这表示一组字符，例如，[abc]表示字符a，b或c中的任何一个。您还可以使用范围，例如[az]用于任何小写字符。
[^...]	集合中字符的补码。例如，[^ A-Za-z]表示除字母字符之外的任何字符。
^	这与行的开头匹配（除非在集合内使用，请参见上文）。
$	这与行尾匹配。
*	这匹配0次或多次。例如，Sa*m比赛Sm， Sam，Saam，Saaam等等。
+	这匹配1次或多次。例如，Sa+m比赛 Sam，Saam，Saaam等等
*/
		;SCI.SEARCHPREV(RegEx,chars)  ;搜索文本所指向的零终止搜索字符串的上一个匹配项
		;SCI.SEARCHNEXT(RegEx,chars)  ;搜索文本所指向的零终止搜索字符串的下一个匹配项
		While (Sci.SearchInTarget(StringLength, "" . String, 2) != -1) {
			TargetStart := Sci.GetTargetStart()
			TargetEnd := Sci.GetTargetEnd()
			If (TargetEnd != SelEnd) {
				Sci.IndicatorFillRange(TargetStart, TargetEnd - TargetStart)
			}
			objPush(Position,[TargetStart,TargetEnd - TargetStart])
			Sci.SetTargetStart(TargetEnd)
			Sci.SetTargetEnd(TextLength)
		}
	}Else{
		Sci.SetIndicatorCurrent(2)
		Sci.IndicatorClearRange(0, Sci.GetLength())
	}
	Return Position
}

change_button_color(label,color){
	Global
	Gui,ColorTheme:Default
	Gui,ColorTheme:Submit,NoHide
	Switch Trim(label)
	{
		case "name":
			GuiControl,ColorTheme:,name,% (color<>""?color:" ")
		case "author":
			GuiControl,ColorTheme:,author,% (color<>""?color:" ")
		case "back_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			GuiControl,ColorTheme:, back_color_pic,% "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,FormatColor_BGR(Color))
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "border_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			GuiControl,ColorTheme:, border_color_pic,% "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,FormatColor_BGR(Color))
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			Gui,ColorTheme:Font,% "s10 norm c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,text_color_pic
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "hilited_text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,hilited_text_color_pic
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "hilited_label_color":
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
			if Color~="i)^\d+$|0x[a-fA-F0-9]+$"{
				Color:=format("0x{:06X}",Color)
			}Else{
				RegExMatch(Trim(ThemeArea,"`r`n"),"(?<=\shilited_candidate_text_color\:\s)[^\r\n]+",match)
				Color:=Trim(match)?format("0x{:06X}",Trim(match)):ColorObj["hilited_candidate_text_color"]
			}
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,hilited_label_color_pic
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
		case "hilited_back_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			GuiControl,ColorTheme:, hilited_back_color_pic,% "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,FormatColor_BGR(Color))
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "hilited_candidate_back_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			GuiControl,ColorTheme:, hilited_candidate_back_color_pic,% "HBITMAP:" . CreateColoredBitmap(PicWidth, PicHeight,FormatColor_BGR(Color))
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "hilited_candidate_text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,hilited_candidate_text_color_pic1
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "hilited_candidate_label_color":
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
			if Color~="i)^\d+$|0x[a-fA-F0-9]+$"{
				Color:=format("0x{:06X}",Color)
			}Else{
				RegExMatch(Trim(ThemeArea,"`r`n"),"(?<=\shilited_candidate_text_color\:\s)[^\r\n]+",match)
				Color:=Trim(match)?format("0x{:06X}",Trim(match)):ColorObj["hilited_candidate_text_color"]
			}
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,hilited_candidate_label_color_pic
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
		case "hilited_comment_text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):ColorObj["hilited_candidate_text_color"]<>""?ColorObj["hilited_candidate_text_color"]:"0x000000"
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,hilited_comment_text_color_pic
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "candidate_text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,candidate_text_color_pic1
			GuiControl,ColorTheme:Font,candidate_text_color_pic2
			GuiControl,ColorTheme:Font,candidate_text_color_pic3
			GuiControl,ColorTheme:Font,candidate_text_color_pic4
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "comment_text_color":
			Color:=Color~="i)^\d+$|0x[a-fA-F0-9]+$"?format("0x{:06X}",Color):"0x000000"
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,comment_text_color_pic1
			GuiControl,ColorTheme:Font,comment_text_color_pic2
			GuiControl,ColorTheme:Font,comment_text_color_pic3
			GuiControl,ColorTheme:Font,comment_text_color_pic4
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
		case "label_color":
			GuiControl,ColorTheme:,ThemeArea,% RegExReplace(Trim(ThemeArea,"`r`n"),"(?<=\s" Label "\:)[^\r\n]+",A_Space color)
			if Color~="i)^\d+$|0x[a-fA-F0-9]+$"{
				Color:=format("0x{:06X}",Color)
			}Else{
				RegExMatch(Trim(ThemeArea,"`r`n"),"(?<=\scandidate_text_color\:\s)[^\r\n]+",match)
				Color:=Trim(match)?format("0x{:06X}",Trim(match)):ColorObj["candidate_text_color"]
			}
			Gui,ColorTheme:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default") " c" SubStr(FormatColor_BGR(Color),3),% DefaultFontName
			GuiControl,ColorTheme:Font,label_color_pic1
			GuiControl,ColorTheme:Font,label_color_pic2
			GuiControl,ColorTheme:Font,label_color_pic3
			GuiControl,ColorTheme:Font,label_color_pic4
			SetButtonColor(label,FormatColor_BGR(Color),"ColorTheme")
			GuiControl,ColorTheme:,%label%,% Color
	}
}

Watch_Select_Color:
	SysGet, _height, 14
	CoordMode,mouse,Screen
	MouseGetPos,xpos, ypos,id
	CursorColor:=GetCursorColor(xpos,ypos),ColorInfo:=FormatColor(CursorColor)
	grayLevel:=GetgrayLevel(ColorInfo)
	Style5 := {Border:1
		, Rounded:5
		, FontSize:13
		, BorderColor:grayLevel < 192?"0xffffffff":"0xff000000"
		, TextColor:grayLevel < 192?"0xffffffff":"0xff000000"
		, BackgroundColorLinearGradientStart:ColorInfo
		, BackgroundColorLinearGradientEnd:ColorInfo
		, BackgroundColorLinearGradientAngle:0
		, BackgroundColorLinearGradientMode:1}
	CursorColor:=StrReplace(ColorInfo,"0xff","0x")
	btt("按LCtrl键终止取色`nRGB：" MatchWeaselItems.StringUpper(SubStr(CursorColor,3)) "`nBGR：" MatchWeaselItems.StringUpper(SubStr(FormatColor_BGR(CursorColor),3)),,,2,Style5,{CoordMode:"Screen"})
	if (CursorColor_last<>CursorColor){
		CursorColor_last:=CursorColor
		SetButtonColor(button_label,CursorColor,"ColorTheme")
		change_button_color(button_label,FormatColor_BGR(CursorColor))
		if sciIsload {
			for Section,element In HighlightIdenticalPos
			{
				Sci.SetSel(element[1],element[1]+element[2])
				ReplaceText:=A_Space button_label ": " FormatColor_BGR(CursorColor)
				SetSelectedText(ReplaceText)
			}
		}
	}
Return

SetSelectedText(Text) {
	Global Sci
	Sci.ReplaceSel("", Text, 1)
}

GetTextRange( Range) {
	Global Sci
	VarSetCapacity(Text, Abs(Range[1] - Range[2]) + 1, 0)
	VarSetCapacity(Sci_TextRange, 8 + A_PtrSize, 0)
	NumPut(Range[1], Sci_TextRange, 0, "UInt")
	NumPut(Range[2], Sci_TextRange, 4, "UInt")
	NumPut(&Text, Sci_TextRange, 8, "Ptr")
	Sci.2162(0, &Sci_TextRange) ; SCI_GETTEXTRANGE
	Return StrGet(&Text,, "UTF-8")
}

Select_Color_func:
	btt("",,,1),btt("",,,2)
	if Select_Color_Mode {
		Select_Color_Mode:=!Select_Color_Mode
		SetTimer, Watch_Select_Color, Off
		Hotkey,$LCtrl,Select_Color_func,Off
		if sciIsload
			HighlightIdenticalText(""),Sci.SetCaretLineBack(0x40FF40),Sci.SETREADONLY(1)
		WinActivate,ahk_id %SetColorTheme%
	}
Return

format_default_preset_color(obj){
	Static preset_color
	preset_color:=""
	for Section,element in obj
	{
		Switch Section
		{
			case "name","author":
				preset_color.="    " Section ": " """" Trim(element,"""") """" "`r`n"
			case "color_scheme":
				Continue
			Default:
				preset_color.="    " Section ": " format("0x{:06X}",Format("0x{:06X}",Trim(element))) "`r`n"
		}
	}

	Return ("  " . obj["color_scheme"] . ":`r`n" . Trim(preset_color,"`r`n"))
}

FormatColor_BGR(Color){
	if Not Color~="i)^\d+$|0x[a-fA-F0-9]{3,6}"
		Return "0x000000"
	Color:=Format("0x{:06X}",Color)
	Return SubStr(Color,1,2) SubStr(Color,7,2) SubStr(Color,5,2) SubStr(Color,3,2)
}

OnAppOptions:
	Gui,AppStates:Destroy
	Gui,AppStates:Default
	OwnerGui:=WinExist("ahk_id " weaselGui)?" +OwnerWeasel ":""
	IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	DefaultFontName:=GetDefaultFontName()
	Gui,AppStates:+Resize -MaximizeBox %OwnerGui% HWNDSetAppState
	Gui,AppStates:margin,20,20
	Gui,AppStates:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,AppStates:margin,15,15
	SysGet, CXVSCROLL, 2
	Gui,AppStates:Font,% "s10 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,AppStates:Add,Button,xm-8 gReloadProcessInfo vReloadProcessInfo,刷`n新
	Gui,AppStates:Add,Button,xm-8 y+10 gControl_State vSubmitAppOptions Disabled,提`n交
	Gui,AppStates:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,AppStates:Add,ListView,x+8 ym r10 w400 gControl_State vshow_app_options AltSubmit Grid +E0x10 -LV0x10 -Multi NoSortHdr -Hdr -WantF2 0x8 LV0x40  LV0x800 LV0x80 HwndHListView,进程|状态|描述 
	LV_ModifyCol(1,160-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,80 " Center"),LV_ModifyCol(3,160 " Center")
	Gosub loadAppOptions
	Gui,AppStates:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui, AppStates:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme":"BackgroundDefault -Theme",
	Gui,AppStates:Show,NA AutoSize ,小狼毫窗口状态管理
	CGuiHeight:=0,CGuiWidth:=0,IsModify:=0,SB_SetParts(350,100)
	SB_SetText(">>双击切换状态，右击更多操作！",1),SB_SetText("总计：" LV_GetCount(),2,"Center")
	WinActivate,ahk_id %SetAppState%
	Gosub ShowProcessDescription
Return

AppStatesGuiSize:
	if A_Cursor In SizeNESW,SizeNS,SizeNWSE,SizeWE
	{
		GuiControlGet,CGSize,AppStates:Pos,show_app_options
		if (!CGuiHeight&&!CGuiWidth&&CGSizeW>350) {
			LV_ModifyCol(1,160-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,80 " Center"),LV_ModifyCol(3,160 " Center")
			Gui, AppStates:+MinSize%A_GuiWidth%x%A_GuiHeight%
		}else if (CGuiHeight&&CGuiWidth&&CGSizeW>350){
			GuiControlGet,CGSize,AppStates:Pos,show_app_options
			GuiControl,AppStates:Move,show_app_options,% "w" CGSizeW+A_GuiWidth-CGuiWidth " h" CGSizeH+A_GuiHeight-CGuiHeight
			LV_ModifyCol(1,(CGSizeW+A_GuiWidth-CGuiWidth)*0.4-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,(CGSizeW+A_GuiWidth-CGuiWidth)*0.2)
			,LV_ModifyCol(3,(CGSizeW+A_GuiWidth-CGuiWidth)*0.4 " Center")
		}
		CGuiHeight:=A_GuiHeight,CGuiWidth:=A_GuiWidth
		SB_SetParts(A_GuiWidth*0.75,A_GuiWidth*0.25),SB_SetText("总计：" LV_GetCount(),2,"Center")
	}
Return

loadAppOptions:
	WeaselYaml_Config:=MatchWeaselItems.GetWeaselYaml()
	Gui,AppStates:Default
	LV_Delete(),AppOptionsList:=WeaselYaml_Config["app_options"]
	for Section,element In AppOptionsList
	{
		LV_Add(A_Index,Section,InStr(element["ascii_mode"],"False")?"中文":"英文")
	}
	SB_SetText("总计：" LV_GetCount(),2,"Center")
Return

Control_State:
	Gui,AppStates:Default
	GuiControlGet, FocusControl, FocusV
	if FocusControl {
		Switch A_GuiControl
		{
			Case "show_app_options":
				RlineInfo:=0
				if (A_GuiEvent="RightClick"){
					RlineInfo:=A_EventInfo
				}Else if (A_GuiEvent="doubleClick"){
					RlineInfo:=A_EventInfo
					Gosub toggleGroupClass
				}
			case "SubmitAppOptions":
				Gui,+OwnDialogs
				MsgBox ,262180,修改确认,此操作不可逆，是否进行修改？
				IfMsgBox,Yes
				{
					if (objCount(AppOptionsList)&&IsModify) {
						if MatchWeaselItems.ModifyWeaselAppOptions(AppOptionsList){
							GuiControl,AppStates:Disable,SubmitAppOptions
							MatchWeaselItems.DeployWeasel()
						}
					}
				}
		}
		EmptyMem()
	}
Return

ReloadProcessInfo:
	Gosub loadAppOptions
	Gosub ShowProcessDescription
Return

ShowProcessDescription:
	Gui,AppStates:Default
	Loop,% LV_GetCount()
	{
		LV_GetText(Names,A_Index,1),LV_GetText(states,A_Index,2)
		Process,Exist,%Names%
		FileDescription:=ErrorLevel?FileGetInfo(GetProcessFullPath(ErrorLevel),"FileDescription"):""
		LV_Modify(A_Index,"text",Names,states,FileDescription?FileDescription:"")
	}
Return

AppStatesGuiContextMenu(GuiHwnd, CtrlHwnd, EventInfo, IsRightClick, X, Y){
	Gui,AppStates:Default
	if (IsRightClick&&A_GuiControl="show_app_options"){
		Menu,GroupClass,Deleteall
		Menu,GroupClass,Add,刷新列表,ReloadProcessInfo
		Menu,GroupClass,Add,
		Menu,GroupClass,Add,切换状态,toggleGroupClass
		Menu,GroupClass,Add,
		Menu,GroupClass,Add,删除状态,deleteGroupClass
		if (EventInfo&&LV_GetNext()) {
			Menu,GroupClass,Enable,切换状态
			Menu,GroupClass,Enable,删除状态
		}else{
			Menu,GroupClass,Disable,切换状态
			Menu,GroupClass,Disable,删除状态
		}
		Menu,GroupClass,Add,
		Menu,GroupClass,Add,添加窗口(中文),addCnGroupClass
		Menu,GroupClass,Add,
		Menu,GroupClass,Add,添加窗口(英文),addEnGroupClass
		Menu,GroupClass,Show
	}
}

deleteGroupClass:
	Gui,AppStates:Default
	if RlineInfo {
		LV_GetText(Names,RlineInfo,1),LV_GetText(states,RlineInfo,2)
		if (Names&&states) {
			LV_Delete(RlineInfo),IsModify++
			objDelete(AppOptionsList,Names)
			GuiControl,AppStates:Enable,SubmitAppOptions
		}
	}
	SB_SetText("总计：" LV_GetCount(),2,"Center")
Return

toggleGroupClass:
	Gui,AppStates:Default
	if RlineInfo {
		LV_GetText(Names,RlineInfo,1),LV_GetText(states,RlineInfo,2)
		if (Names&&states) {
			Switch states
			{
				Case "中文":
					LV_Modify(RlineInfo,"text",Names,"英文"),IsModify++
					AppOptionsList[Names,"ascii_mode"]:="true"
				Case "英文":
					LV_Modify(RlineInfo,"text",Names,"中文"),IsModify++
					AppOptionsList[Names,"ascii_mode"]:="false"
			}
			GuiControl,AppStates:Enable,SubmitAppOptions
		}
	}
	SB_SetText("总计：" LV_GetCount(),2,"Center")
Return

addCnGroupClass:
	Gui,AppStates:Default
	Hotkey,$LCtrl,Select_Color_func,Off
	initstate:=True,Get_Process_Mode:=1,btt("",,,1),btt("",,,2)
	Hotkey,$LCtrl,Select_Process_func,On
	SetTimer, WatchCursorGui, 100
Return

addEnGroupClass:
	Gui,AppStates:Default
	Hotkey,$LCtrl,Select_Color_func,Off
	initstate:=False,Get_Process_Mode:=1,btt("",,,1),btt("",,,2)
	Hotkey,$LCtrl,Select_Process_func,On
	SetTimer, WatchCursorGui, 100
Return

WatchCursorGui:
	SysGet, _height, 14
	CoordMode,mouse,Screen
	MouseGetPos,xpos, ypos,id
	WinGet, CursorProcessPath, ProcessPath , ahk_id %id%
	WinGet,CursorProcessName,ProcessName,ahk_id %id%
	CursorColor:=GetCursorColor(xpos,ypos),ColorInfo:=FormatColor(CursorColor)
	grayLevel:=GetgrayLevel(ColorInfo),FileDescription:=FileGetInfo(CursorProcessPath,"FileDescription")
	Style5 := {Border:1
		, Rounded:5
		, FontSize:13
		, BorderColor:grayLevel < 192?"0xffffffff":"0xff000000"
		, TextColor:grayLevel < 192?"0xffffffff":"0xff000000"
		, BackgroundColorLinearGradientStart:ColorInfo
		, BackgroundColorLinearGradientEnd:ColorInfo
		, BackgroundColorLinearGradientAngle:0
		, BackgroundColorLinearGradientMode:1}

	btt("按LCtrl终止识别`n进程名：" CursorProcessName (FileDescription?"`n进程描述：" FileDescription:""),,,1,Style5,{CoordMode:"Screen"})
Return

Select_Process_func:
	btt("",,,1)
	if Get_Process_Mode {
		Get_Process_Mode:=!Get_Process_Mode
		SetTimer, WatchCursorGui, Off
		Hotkey,$LCtrl,Select_Process_func,Off
		if CursorProcessName&&!objCount(AppOptionsList[CursorProcessName]) {
			Gui,AppStates:Default
			GuiControl,AppStates:Enable,SubmitAppOptions
			LV_Add(LV_GetCount(),CursorProcessName:=MatchWeaselItems.StringLower(CursorProcessName),initstate?"中文":"英文",FileDescription<>1?FileDescription:"")
			AppOptionsList[CursorProcessName,"ascii_mode"]:=initstate?"false":"true"
			SB_SetText("总计：" LV_GetCount(),2,"Center"),IsModify++
		}
		WinActivate,ahk_id %SetAppState%
	}
Return

AppStatesGuiClose:
	Gui,AppStates:Destroy
	btt("",,,1),AppOptionsList:={},IsModify:=0
	EmptyMem()
Return

WeaselGuiClose:
	Gui,Weasel:Destroy
	Submit_candidate:={},Submit_Style:={},Submit_Installation:={},Submit_Themes:=""
	Submit_switcher:={},Submit_Default:={},PreviewDock:={},EmptyMem()
Return

Split_Select_labels(chars){
	Static tarr,index,Count
	tarr:="", index:=1,Count:=0
	chars:=RegExReplace(chars,"[\s\t\r\n]")
	While index:=RegExMatch(chars, "O).", match, index)
	{
		if match.Value {
			tarr.=(match.Value~="^\d+$"?"":"""") Trim(match.Value) (match.Value~="^\d+$"?"":"""") ",", index+=match.Len,Count++
		}
	}
	return Count>8?"[" Trim(tarr,",") "]":"-1"
}
;;============================================================================================
GetFontslist(){
	static fontlist
	fontlist:=""
	If (fontlist)
		Return fontlist
	VarSetCapacity(logfont, 128, 0), NumPut(1, logfont, 23, "UChar")
	obj := []
	DllCall("EnumFontFamiliesEx", "ptr", DllCall("GetDC", "ptr", 0), "ptr", &logfont, "ptr", RegisterCallback("EnumFontProc"), "ptr", &obj, "uint", 0)
	For font in obj
		fontlist .= "|" font
	fontlist:=LTrim(fontlist,"|")
	Return fontlist
}
EnumFontProc(lpFont, tm, TextFont, lParam){
	obj := Object(lParam)
	If (TextFont>1&&!InStr(font:=StrGet(lpFont+28), "@"))
		obj[font] := 1
	Return 1
}

MoveActiveWindows( p_w, p_l, p_m, p_hw ){
	PostMessage, 0xA1, 2
}

WM_MOUSEMOVE( p_w, p_l, p_m, p_hw){
	Global Select_Color_Mode
	Tip_Show:={candidate_spacing:"style/layout/candidate_spacing: 候选项之间的间隔",horizontal:"style/horizontal: 候选框横排",spacing:"style/layout/spacing: 编码与词条栏间隔",min_width:"style/layout/min_width: 指定候选框宽度最小值",round_corner:"style/layout/round_corner: 焦点高亮色块圆角"
		,margin_y:"style/layout/margin_y: 候选字上下边距",margin_x:"style/layout/margin_x: 候选字左右边距",inline_preedit:"style/inline_preedit: 内嵌编码模式单行显示开关（仅支持TSF）",hilite_padding:"style/layout/hilite_padding: 焦点高亮色块高度 ",font_point:"style/font_point: 候选框字号"
		,hilite_spacing: "style/layout/hilite_spacing: 序号和候选字之间的间隔",min_height:"style/layout/min_height: 指定候选框高度最小值",fullscreen:"style/fullscreen: 全屏的输入窗口"
		,page_size:"候选词待选数量",preedit_type:"style/preedit_type: 嵌入方式/内嵌编码模式开启有效`n（preview嵌入首选、composition嵌入编码、input嵌入输入码）",font_face:"style/font_face: 候选框字体",color_scheme:"style/color_scheme:选择主题配色",set_app_options:"配置每个窗口的中英输入状态"
		,alternative_select_labels:"更改候选项序号标签",display_tray_icon:"显示小狼毫托盘状态图标",change_theme:"自定义配置主题",size:"显示历史上屏词条，一般配置在z键！",enable_completion:"开启逐码提示，显示编码提示",hide_candidate:"隐藏候选框盲打！"
		,max_code_length:"指定编码码长",auto_select:"在指定码长的情况下，`n候选唯一自动上屏",Toggle_State:"switches开关项状态，`n必须操作此项才有效！",switchelists:"switches开关组，切换后`n需要操作勾选项才生效！"
		,back_color: "back_color: 候选框底色（16进制BGR色值）",border_color: "border_color: 候选框边框色（16进制BGR色值）",text_color: "text_color: 已选择文本字色（16进制BGR色值）",hilited_text_color: "hilited_text_color: 编码项字色（16进制BGR色值）",hilited_back_color: "hilited_back_color: 编码项背景色（16进制BGR色值）",hilited_candidate_back_color: "hilited_candidate_back_color: 焦点高亮色块背景颜色（16进制BGR色值）"
		,hilited_candidate_text_color: "hilited_candidate_text_color: 焦点高亮色块候选字色（16进制BGR色值）",hilited_comment_text_color: "hilited_comment_text_color: 焦点高亮项注解文字色（16进制BGR色值）",candidate_text_color: "candidate_text_color: 候选项文字颜色（16进制BGR色值）",comment_text_color: "comment_text_color: 注解文字颜色（16进制BGR色值）"
		,hilited_label_color:"hilited_label_color: 焦点高亮候选项序号标签字色，Win（16进制BGR色值）",hilited_candidate_label_color:"hilited_candidate_label_color: 首选项序号标签字色，Mac（16进制BGR色值）"
		,label_color: "label_color: 其它非选中候选项序号标签字色（16进制BGR色值）",CopyTheme_1:"复制配色代码至剪切板",SaveTheme:"写入小狼毫主题配置文件",ShowSchemalistbox_left:"方案列表栏，双击添加至右边",ShowSchemalistbox_right:"已启用方案列表栏，双击删除"
		,Toggle_CapsClear:"有候选的时候，Capslock清屏并不触发本身",Toggle_SymbolsTip:"/引导特殊符号时显示提示窗口，输入//触发",SelectHotkey:"设置小狼毫方案选单热键，`n受输入法限制可设置的热键`n不多，设置了不一定有效！"
		,SelectSchema:"自由选择加载的方案",AddWeaselHotkey:"按下此键15秒内录制组合键，自动识别",ShowHotkeylistbox:"双击行删除热键",CancelOption:"重置此前的操作",select_sync_dir:"更换小狼毫自带用户资料同步目录"
		,SelectProcessPath:"手动选择exe启动文件路径",GetProcessPath:"自动识别窗口进程路径",SelectScriptPath:"如果参数是脚本请手动选择脚本路径",Toggle_filter_extend:"设置字体的时候过滤超集方案"
		,extend_theme_list:"工具内置的主题配色，如果配色存在`n则「添加」按钮为禁用状态，反之！",save_extend_theme:"添加主题配色至配置文件"}
	CurRControl := A_GuiControl
	if (CurRControl <> PrevControl and not InStr(CurRControl, " ") And !Select_Color_Mode)
	{
		btt(Tip_Show[CurRControl],,,1,,{CoordMode:"Screen"})
		PrevControl := CurRControl
	}Else{
		btt("",,,1)
		if !Select_Color_Mode
			btt("",,,2)
	}
}

ShellIMEMessage( wParam,lParam ) {
	/*    wParam参数：
		;1 顶级窗体被创建 	;2 顶级窗体即将被关闭 	;54 退出全屏	;32772 窗口切换
		;3 SHELL 的主窗体将被激活 	;4 顶级窗体被激活 	;&H8000& 掩码 	;53 全屏
		;5 顶级窗体被最大化或最小化 	;6 Windows 任务栏被刷新，也可以理解成标题变更
		;7 任务列表的内容被选中 	;8 中英文切换或输入法切换 	;13 wParam=被替换的顶级窗口的hWnd 
		;9 显示系统菜单 	;10 顶级窗体被强制关闭 	;14 wParam=替换顶级窗口的窗口hWnd
		;12 没有被程序处理的APPCOMMAND。见WM_APPCOMMAND
	*/

	Global WeaselRoot,InstallDir,RimeUserDir,ServerExecutable,IsServer,weaselGui,SetAppState,load_complete,presetTheme
		,SetColorTheme,UserDictGui,extendedGui,SetAutoTask,StartTime,ExtendSchemaId,Switches_list,previewTheme
	Static thistime
	thistime:=SubStr(A_Now,1,12)
	EnvSub, thistime, %StartTime%, Minutes
	DetectHiddenWindows, On
	if !WinExist("ahk_id " previewTheme){
		ShowPreviewGui(1)
	}
	DetectHiddenWindows, Off
	if (thistime>30&&!WinExist("ahk_id " weaselGui)&&!WinExist("ahk_id " SetAppState)&&!WinExist("ahk_id " SetColorTheme)&&!WinExist("ahk_id " UserDictGui)&&!WinExist("ahk_id " extendedGui)&&!WinExist("ahk_id " SetAutoTask)){
		OnReload()
	}

	if (A_Is64bitOS&&A_PtrSize>4){
		SetRegView, 64
	}
	RegRead, WeaselRoot, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, WeaselRoot
	RegRead, InstallDir, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, InstallDir
	RegRead, ServerExecutable, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, ServerExecutable
	RegRead, RimeUserDir, HKEY_CURRENT_USER\Software\Rime\Weasel, RimeUserDir
	RimeUserDir:=RimeUserDir?RimeUserDir:FileExist(A_AppData "\Rime\*.yaml")?A_AppData "\Rime":""
	ServerExecutable:=ServerExecutable?RegExReplace(Trim(ServerExecutable,""""),".+\\"):"WeaselServer.exe"
	if (RimeUserDir&&!WeaselRoot){
		Process,Exist,%ServerExecutable%
		if ErrorLevel
			WeaselRoot:=RegExReplace(GetProcessFullPath( ErrorLevel ),"\\[^\\]+$")
	}
	if FileExist(WeaselRoot "\" ServerExecutable) {
		Menu,tray,Enable,程序目录
		Menu,tray,Enable,用户目录
		Menu,tray,Enable,重新部署
		if load_complete {
			Menu,tray,Enable,自定义
			Menu,tray,Enable,设置窗口
		}
		ExtendSchemaId:=ExtendSchemaId?ExtendSchemaId:GetExtendSchemaId()
		Switches_list:=objCount(switches_list)?switches_list:GetSwitcherAllList()
		if WinExist("ahk_id " weaselGui){
			if ExtendSchemaId
				GuiControl,Weasel:Enable,Toggle_filter_extend
			Else
				GuiControl,Weasel:Disable,Toggle_filter_extend
		}
	}else{
		Menu,tray,Disable,程序目录
		Menu,tray,Disable,用户目录
		Menu,tray,Disable,重新部署
		if load_complete {
			Menu,tray,Disable,自定义
			Menu,tray,Disable,设置窗口
		}
		ExtendSchemaId:="",Switches_list:={}
		if WinExist("ahk_id " weaselGui){
			GuiControl,Weasel:Disable,Toggle_filter_extend
		}
	}
	Process, Exist , %ServerExecutable%
	if ErrorLevel {
		Menu, Tray, check, 算法服务
		if !IsServer {
			IsServer:=!IsServer
		}
	}Else{
		Menu, Tray, Uncheck, 算法服务
		Menu, Tray, Icon, 算法服务,shell32.dll,234
		if IsServer {
			IsServer:=!IsServer
			if FileExist(WeaselRoot "\" ServerExecutable){
				TrayTip,小狼毫助手,小狼毫算法服务已终止，请在托盘菜单启用！,,3
			}else{
				TrayTip,小狼毫助手,%ServerExecutable%不存在！,,3
			}
		}
	}

	WinWait , %A_ScriptName%, , 1
	;消除重复运行程序时弹出”Could not close the previous instance of this script. Keep waiting“窗口
	ControlGetText, WinStaticText , Static1,ahk_class #32770
	if WinExist(A_ScriptName)&&InStr(WinStaticText,"keep Waiting"){   ;ahk_class #32770
		WinActivate,ahk_class #32770
		ControlFocus,Button1
		ControlSend , Button1, {Enter}, A
		if WinExist(A_ScriptName) {
			SendInput,{Enter}
		}
		OnReload()
	}
	Gosub TrayMenuTip
	EmptyMem()
}

OnAbout(){
	Run, https://gitee.com/leeonchiu/rime-tools-for-wubi98/releases,, UseErrorLevel
	if (ErrorLevel = "ERROR") {
		Run, iexplore.exe "https://gitee.com/leeonchiu/rime-tools-for-wubi98/releases",, UseErrorLevel
		if (ErrorLevel = "ERROR"){
			Run, msedge.exe "https://gitee.com/leeonchiu/rime-tools-for-wubi98/releases",, UseErrorLevel
		}
	}
}

OnHelp(){
	Run, http://fds8866.ys168.com/,, UseErrorLevel
	if (ErrorLevel = "ERROR") {
		Run, iexplore.exe "http://fds8866.ys168.com/",, UseErrorLevel
		if (ErrorLevel = "ERROR"){
			Run, msedge.exe "http://fds8866.ys168.com/",, UseErrorLevel
		}
	}
}

AutoRunTool:
	if IsAutoRun:=EnableAutoRun(TaskName,"小狼毫辅助工具",(A_IsCompiled?A_ScriptFullPath:A_AhkPath),!A_IsCompiled?A_ScriptFullPath:"") {
		if (IsAutoRun=1){
			Menu, Tray, Uncheck, 开机自启
			Menu, Tray, Icon, 开机自启,shell32.dll,234
			traytip,小狼毫助手,已取消开机自启计划任务！,,1
		}Else if (IsAutoRun<0){
			MsgBox, 262160, Error,添加异常！,8
		}Else if (IsAutoRun=TaskName){
			Menu, Tray, Check, 开机自启
			traytip,小狼毫助手,已建立开机自启计划任务！,,1
		}
	}else{
		Menu, Tray, Uncheck, 开机自启
		Menu, Tray, Icon, 开机自启,shell32.dll,234
		traytip,Error,建立开机自启计划任务失败！,,3
	}
Return


ToggleRunWeasel:
	MatchWeaselItems.ToggleRunWeasel()
Return

GotoRimeUserDir(){
	global RimeUserDir
	if FileExist(RimeUserDir "\build"){
		OpenAndSelect(RimeUserDir "\build")
	}
}

GotoWeaselRootDir(){
	global WeaselRoot
	if FileExist(WeaselRoot "\data\"){
		OpenAndSelect(WeaselRoot "\data\default.yaml")
	}
}

GetUserDict(){
	Global
	DefaultFontName:=GetDefaultFontName()
	IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	Gui,Rime:Destroy
	Gui,Rime:Default
	Gui,Rime: +HWNDUserDictGui +LastFound
	Gui,Rime:Font,% "s12 bold " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Rime:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui,Rime:Add,GroupBox,y+10 vGroupBox1,小狼毫自造词提取
	GuiControlGet,gbpos,Rime:Pos,GroupBox1
	Gui,Rime:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
	Gui,Rime:Add,text,% "xp+20 y" gbposY+35 " w450 cA0A0A0 vhk_tip",在打字时选字焦点移至候选框中要删除的自造词组上，配合组合键「Shift+Delete、Ctrl+Delete」删除，MacOS操作热键：「Shift+Fn+Delete」。本页面删除操作只为提取并不能控制词库，快捷键只能删除自造词对主码表无效！先「同步用户资料」再进行提取操作！小狼毫超强两笔系列专用。
	Gui,Rime:Font,s11 bold,% DefaultFontName
	Gui,Rime:Add,ListBox,% "xp y+10 R10 w105 gShowSchemaList vShowSchemaList Center 0x1000 0x100",% (AllSchemaName:=GetSchemaList())
	GuiControlGet,hkpos,Rime:Pos,hk_tip
	Gui,Rime:Font,s10 norm,% DefaultFontName
	Gui,Rime:Add,Button,x+5 yp gSyncToUserDir vSyncToUserDir,同`n步
	Gui,Rime:Add,Button,xp y+8 gReloadWeasel vReloadWeasel,部`n署
	Gui,Rime:Add,Button,xp y+8 gGotoRimeUserDir vGotoRimeUserDir,用`n户`n目`n录
	Gui,Rime:Add,Button,xp y+8 gGotoWeaselRootDir vGotoWeaselRootDir,程`n序`n目`n录
	Gui,Rime:Font,s10 norm,% DefaultFontName
	SysGet, CXVSCROLL, 2
	Gui,Rime:Add,ListView,% "x+5 y" hkposY+hkposH+10 " r18 w280 gShowSchemaCizu vShowSchemaCizu AltSubmit Grid -LV0x10 -Multi -Hdr NoSortHdr -WantF2 0x8 LV0x40  LV0x800 LV0x80",词组|编码|词频
	Gui,Rime:Font,s10 norm,% DefaultFontName
	Gui,Rime:Add,Button,xp y+10 gControl_Gui vExportDict1,导出词条
	Gui,Rime:Add,Button,x+10 yp gControl_Gui vExportDict2,合并导出
	Gui,Rime:Add,Button,x+10 yp gControl_Gui vAddCitiao,新增扩展词
	Gui,Rime:Add,Button,x+10 yp gControl_Gui vDeleteUserDict,清空自造词
	LV_ModifyCol(1,130-CXVSCROLL/(A_ScreenDPI/96)),LV_ModifyCol(2,75 " Left"),LV_ModifyCol(3,75 " Center")
	GuiControlGet,lbpos,Rime:Pos,ShowSchemaCizu
	GuiControlGet,sudpos,Rime:Pos,SyncToUserDir
	GuiControlGet,ecpos,Rime:Pos,ExportDict1
	GuiControlGet,ecpos4,Rime:Pos,DeleteUserDict
	GuiControl,Rime:Move,ShowSchemaList,% "h" lbposH+ecposH+18
	GuiControl,Rime:Move,ShowSchemaCizu,% "x" (ecpos4X-ecposX+ecpos4W-lbposW)/2+ecposX
	GuiControlGet,scpos,Rime:Pos,ShowSchemaList
	GuiControl,Rime:Move,GroupBox1,% "h" lbposH+ecposH+75+hkposH " w" lbposW+scposW+60+(ecpos4X-ecposX+ecpos4W-lbposW)/2+sudposW
	GuiControl,Rime:Move,SyncToUserDir,% "x" sudposX+(ecpos4X-ecposX+ecpos4W-lbposW)/4
	GuiControl,Rime:Move,ReloadWeasel,% "x" sudposX+(ecpos4X-ecposX+ecpos4W-lbposW)/4
	GuiControl,Rime:Move,GotoRimeUserDir,% "x" sudposX+(ecpos4X-ecposX+ecpos4W-lbposW)/4
	GuiControl,Rime:Move,GotoWeaselRootDir,% "x" sudposX+(ecpos4X-ecposX+ecpos4W-lbposW)/4
	Gui,Rime:Show,AutoSize,小狼毫自造词提取
	for key,value in ["ExportDict1","ExportDict2","AddCitiao","DeleteUserDict"]
		GuiControl,Rime:Disable,%value%
	SyncToUserDir()
}

FormatTipString(str){
	list:=""
	Loop,Parse,str,`|
	{
		list:=!Mod(A_Index,4)?Trim(list,"、") "`n   " A_LoopField:list "、" A_LoopField 
	}
	Return list
}

closeGui(){
	Global UserDictGui,OptionType
	Switch A_GuiControl
	{
		case "closeGui_1":
			Gui,Rime:Destroy
			EmptyMem()
		case "closeGui_2":
			WinMinimize , ahk_id %UserDictGui%
			EmptyMem()
	}
}

GetMainDictPath(DictPath){
	if FileExist(DictPath){
		FileContent:=GetFileContent(DictPath)
		if RegExMatch(FileContent,"O)(import\_tables\:\r\n\s+\-\s+)(\w+)",match){
			if FileExist(DictPath:=RegExReplace(DictPath,"[^\\]+$") RegExReplace(match.value(2),"^[\s\t\r\n]+|[\s\t\r\n]+$") ".dict.yaml")
				Return DictPath
		}
	}
}

ExportAllCitiao(){
	Global FileLists,WeaselRoot,RimeUserDir,ServerExecutable
	Static  result,SelectedFile,ShowSchemaList,schemadictpath,FileContent,Dict,bianma,citiao,Content
	if FileExist(userdbfilepath:=Getuserdbfilepath()){
		result:="",SyncToUserDir()
		sleep 8000
		Gui,Rime:Default
		GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
		if schemadictpath:= FileLists[ShowSchemaList]{
			traytip,Notify, 文件处理中请稍候。。。,,1
			if InStr(schemadictpath,".src.dict."){
				if MainDictPath:=GetMainDictPath(schemadictpath){
					schemadictpath:= MainDictPath
				}Else{
					TrayTip,Error,词典文件路径获取失败！,,3
					Return
				}
			}
			Content:=GetFileContent(schemadictpath)
			if objCount(UserDict:=GetUserdbList(userdbfilepath)){
				for Section,element In UserDict
				{
					RegExMatch(Content,"(?<=[^\t\r\n]\t" RegExReplace(element,"[^\w]") "\t)\d+",match)
					result.= Section A_Tab element A_Tab (match?(match>1?match-1:match):10000) "`r`n"
				}
				if result:=Trim(result,"`r`n"){
					Gui +OwnDialogs 
					FileSelectFile, SelectedFile, S11, %A_Desktop%\%A_Now%.txt, 选择保存文件的位置, Text Documents (*.txt)
					if (SelectedFile<>""){
						SelectedFile:=FileExist(SelectedFile)?RegExReplace(SelectedFile,"(\.\w+$)","-" A_Now "$1"):SelectedFile
						FileAppend,%result%, %SelectedFile%,UTF-8
						OpenAndSelect(SelectedFile)
						TrayTip,小狼毫助手,自造词导出成功！,,1
					}
				}
			}
			EmptyMem()
		}
	}
}

Control_Gui(){
	Global FileLists,WeaselRoot,RimeUserDir,ServerExecutable
	Static  result,SelectedFile,ShowSchemaList,schemadictpath,FileContent,Dict,bianma,citiao,Content
	if !FileExist(WeaselRoot "\data"){
		Process,Exist,%ServerExecutable%
		if ErrorLevel
			traytip,Error, 无法获取小狼毫注册表安装路径，请重装修复后使用！,,2
		Else
			traytip,Error, 无法获取小狼毫安装路径，可能该机未装小狼毫！,,3
		Return
	}
	Switch A_GuiControl
	{
		case "ExportDict1":
			ExportAllCitiao()
		case "ExportDict2":
			GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
			if schemadictpath:=FileLists[ShowSchemaList] {
				SyncToUserDir()
				sleep 8000
				if InStr(schemadictpath,".src.dict."){
					if MainDictPath:=GetMainDictPath(schemadictpath){
						schemadictpath:= MainDictPath
					}Else{
						TrayTip,Error,词典文件路径获取失败！,,3
						Return
					}
				}
				SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
				if FileContent:=GetFileContent(schemadictpath,"UTF-8",1){
					TrayTip,小狼毫助手,正在合并导出中，请稍候。。。,,1
					FileContent:=RegExReplace(FileContent,"[\t\s]{1,}\r\n","`r`n")
					if headerContent:=RegExReplace(FileContent,"(\r\n[^\r\n\t]+)(\t[^\r\n\t]+){1,4}|[\t\s]{1,}\r\n","`r`n") {
						headerContent:=RegExReplace(RTrim(headerContent, "`r`n"),"(\r\n[\#]+[^\r\n\t]+)+$")
						Dict:= StrReplace(FileContent,RTrim(headerContent,"`r`n"))
						if (FileContent<>Dict){
							flag:=1
						}Else{
							Dict:="",flag:=2
						}
					}Else{
						flag:=3
					}
				}
				if FileExist(userdbfilepath:=Getuserdbfilepath()){
					if objCount(UserDict:=GetUserdbList(userdbfilepath)){
						for Section,element In UserDict
						{
							RegExMatch(FileContent,"(?<=[^\t\r\n]\t" RegExReplace(element,"[^\w]") "\t)\d+",match)
							result.= (A_Index=1?"##################自造词##################`r`n`r`n":"`r`n") Section "`t" element "`t" (match?(match>1?match-1:match):10000)
						}
					}
				}
				result:=RegExReplace(Dict,"(*BSR_ANYCRLF)\R+", "`r`n") "`r`n`r`n" result,DictFileName:=A_Desktop "\" name_no_ext "-" A_Now ".txt"
				FileAppend,% Trim(result,"`r`n"),%DictFileName%,UTF-8
				if (flag=1)
					TrayTip,小狼毫助手,合并导出成功！,,1
				Else if (flag=2)
					TrayTip,小狼毫助手,「%name%」处理失败！,,2
				Else if (flag=3)
					TrayTip,小狼毫助手,「%name%」读取失败！,,2
				OpenAndSelect(DictFileName)
			}
			EmptyMem()
		case "AddCitiao":
			extendDictGui()
		case "DeleteUserDict":
			Gui,+OwnDialogs
			MsgBox,262180,小狼毫助手,是否删除自造词文件？
			IfMsgBox,Yes
			{
				GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
				if schemadictpath:=FileLists[ShowSchemaList] {
					if InStr(schemadictpath,".src.dict."){
						if MainDictPath:=GetMainDictPath(schemadictpath){
							schemadictpath:= MainDictPath
						}Else{
							TrayTip,Error,词典文件路径获取失败！,,3
							Return
						}
					}
					SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
					Process,Close,%ServerExecutable%
					if ErrorLevel {
						if FileExist(RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")){
							Gui,Rime:Default
							LV_Delete()
							FileRecycle,% RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")
						}
						Run *RunAs "%WeaselRoot%\%ServerExecutable%" /restart
						TrayTip,小狼毫助手,% "文件「" RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt") "」删除成功！"
					}
				}
			}
	}
}

extendDictGui(){
	Global
	GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
	if objCount(FileLists){
		IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
		Gui,extended:Destroy
		Gui,extended:Default
		Gui,extended:+Resize +OwnerRime -MinimizeBox HWNDextendedGui
		Gui,extended:margin,20,20
		Gui,extended:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
		Gui,extended:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
		Gui,extended:margin,15,15
		Gui,extended:Add,Button,xm-8 gReloadExtendDict,刷`n新
		Gui,extended:Add,Button,xm-8 y+5 gReloadWeasel ,部`n署
		Gui,extended:Add,Button,xm-8 y+5 gViewExtendDict vViewExtendDict,定`n位
		Gui,extended:Add,Button,xm-8 y+5 gImportExtendDict vImportExtendDict,导`n入
		GuiControl,extended:Disable,ViewExtendDict
		Gui,extended:Add,ListView,x+8 ym r10 w500 gShowExtendDict vShowExtendDict AltSubmit Grid +E0x10 -LV0x10 -Multi NoSortHdr -WantF2 0x8 LV0x40  LV0x800 LV0x80 HwndHListView,词条|编码|词频
		LV_ModifyCol(1,300-CXVSCROLL/(A_ScreenDPI/96)),LV_ModifyCol(2,100),LV_ModifyCol(3,100 " Center")
		Gui,extended:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"),% DefaultFontName
		Gui, extended:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme HWNDHSbar":"BackgroundDefault -Theme HWNDHSbar",
		Gui,extended:Show,AutoSize
		SB_SetParts(460,150),CGuiHeight:=0,CGuiWidth:=0,loadingListView()
	}
}

extendedGuiSize:
	if A_Cursor In SizeNESW,SizeNS,SizeNWSE,SizeWE
	{
		GuiControlGet,CGSize,extended:Pos,ShowExtendDict
		if (!CGuiHeight&&!CGuiWidth&&CGSizeW>350) {
			LV_ModifyCol(1,160-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,80 " Center"),LV_ModifyCol(3,160 " Center")
			Gui, extended:+MinSize%A_GuiWidth%x%A_GuiHeight%
		}else if (CGuiHeight&&CGuiWidth&&CGSizeW>350){
			GuiControlGet,CGSize,extended:Pos,ShowExtendDict
			GuiControl,extended:Move,ShowExtendDict,% "w" CGSizeW+A_GuiWidth-CGuiWidth " h" CGSizeH+A_GuiHeight-CGuiHeight
			LV_ModifyCol(1,(CGSizeW+A_GuiWidth-CGuiWidth)*0.6-CXVSCROLL*(A_ScreenDPI/96)),LV_ModifyCol(2,(CGSizeW+A_GuiWidth-CGuiWidth)*0.2)
			,LV_ModifyCol(3,(CGSizeW+A_GuiWidth-CGuiWidth)*0.2 " Center")
		}
		CGuiHeight:=A_GuiHeight,CGuiWidth:=A_GuiWidth
		SB_SetParts(A_GuiWidth*0.8,A_GuiWidth*0.2),SB_SetText("总计：" LV_GetCount(),2,"Center")
	}
Return

loadingListView(){
	Global FileLists,RimeUserDir,WeaselRoot,DefaultFontName,CXVSCROLL,extendedGui,ShowSchemaList
	Static extendDict
	if objCount(FileLists){
		Gui,Rime:Default
		GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
		Gui,extended:Default
		schemadictpath:=FileLists[ShowSchemaList]
		if InStr(schemadictpath,".src.dict."){
			if MainDictPath:=GetMainDictPath(schemadictpath){
				schemadictpath:= MainDictPath
			}Else{
				TrayTip,Error,词典文件路径获取失败！,,3
				Return
			}
		}
		SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
		extendDict:= RegExReplace(name,"i)\.dict.",".src.dict.")
		extendDict:= FileExist(RimeUserDir "\" extendDict)?RimeUserDir "\" extendDict:FileExist(WeaselRoot "\data\" extendDict)?WeaselRoot "\data\" extendDict:""
		Gui,extended:Default
		WinSetTitle, ahk_id %extendedGui%, ,% extendDict?extendDict:"扩展词管理"
		if extendDict
			GuiControl,extended:Enable,ViewExtendDict
		Else
			GuiControl,extended:Disable,ViewExtendDict
		if FileContent:=GetFileContent(extendDict){
			if objCount(DictObj:=FormatExtendDict(FileContent)){
				for Section,element In DictObj
				{
					for key,value In element
						LV_Add(A_Index,Section,value[1],value[2])
				}
			}
		}
		SB_SetText("总计：" LV_GetCount() "行",2,"Center"),SB_SetText(ShowSchemaList?">>方案:「 " ShowSchemaList " 」；批量导入后会自动部署生效，删除词条后需手动部署生效！":"导入后会自动部署生效，删除词条后需手动部署生效！",1),EmptyMem()
	}
}

ImportExtendDict(){
	Global extendedGui
	WinGetTitle, Title, ahk_id %extendedGui%
	if FileExist(Title:=RegExReplace(Title,"i)(?<=\w\.yaml).+")){
		Gui,+OwnDialogs
		FileSelectFile, SelectedFile, 3, %A_Desktop%\, 请选择单行单义的txt码表文件, Text Documents (*.txt)
		if (SelectedFile<>""){
			FileContent:=GetFileContent(SelectedFile),result:="",Count:=0,Index:=0
			if FileContent~="\n*[^\x00-\xff]+[\t\s]*|\n*[^\x00-\xff]+\t\t\d+[\t\s]*|\n*[^\t\r\n]+\t\w+[\t\s]*|\n*[^\t\r\n]+\t\w+\t\d+[\t\s]*"{
				Gui,extended:Default
				all:=Trim(GetFileContent(Title,"UTF-8",1)) "`r`n"
				Loop,Parse,FileContent,`n,`r
				{
					if Trim(A_LoopField){
						tarr:=strSplit(Trim(A_LoopField),"`t"),Index++
						if Not all~= "\r\n\s*" Trim(tarr[1] A_Tab tarr[2] A_Tab tarr[3]) "[\s\t]*\r\n"&&tarr[1]{
							LV_Add(LV_GetCount(),tarr[1],tarr[2],tarr[3]),Count++
							result.=Trim(tarr[1] A_Tab tarr[2] A_Tab tarr[3]) "`r`n"
						}
					}
				}

				if result {
					if all~="[\x00-\xff]+" {
						all:=Trim(all) . "`r`n" . result
						FileDelete,%Title%
						FileAppend,%all%,%Title%,UTF-8
						Traytip,小狼毫助手,% "导入成功，添加" Count "条" (Index-Count>0?"，重复" Index-Count "条。":"。"),,1
						ReloadWeasel()
					}
				}
			}
			SB_SetText("总计：" LV_GetCount() "行",2,"Center"),EmptyMem()
		}
	}
}

extendedGuiContextMenu(GuiHwnd, CtrlHwnd, EventInfo, IsRightClick, X, Y){
	Global FileLists,ShowSchemaList,RimeUserDir,WeaselRoot
	Gui,Rime:Default
	GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
	if objCount(FileLists)&&FileLists[ShowSchemaList]{
		if InStr(schemadictpath:=FileLists[ShowSchemaList],".src.dict."){
			if MainDictPath:=GetMainDictPath(schemadictpath){
				schemadictpath:= MainDictPath
			}Else{
				TrayTip,Error,词典文件路径获取失败！,,3
				Return
			}
		}
		SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
		extendDict:= RegExReplace(name,"i)\.dict.",".src.dict.")
		extendDict:= FileExist(RimeUserDir "\" extendDict)?RimeUserDir "\" extendDict:FileExist(WeaselRoot "\data\" extendDict)?WeaselRoot "\data\" extendDict:""
	}
	Gui,extended:Default
	if (IsRightClick&&A_GuiControl="ShowExtendDict"){
		Menu,extendedDict,Deleteall
		Menu,extendedDict,Add,刷新列表,ReloadExtendDict
		Menu,extendedDict,Add,
		Menu,extendedDict,Add,批量写入,AddItem
		if !FileExist(extendDict)
			Menu,extendedDict,Disable,批量写入
		Menu,extendedDict,Add,
		Menu,extendedDict,Add,复制词条,CopyItem
		Menu,extendedDict,Add,
		Menu,extendedDict,Add,导出全部,ExportAllextendCitiao
		Menu,extendedDict,Add,
		Menu,extendedDict,Add,删除词条,DeleteItem2
		if (EventInfo&&LV_GetNext()) {
			Menu,extendedDict,Enable,删除词条
			Menu,extendedDict,Enable,复制词条
			Menu,extendedDict,Enable,导出全部
		}else{
			Menu,extendedDict,Disable,删除词条
			Menu,extendedDict,Disable,复制词条
			Menu,extendedDict,Disable,导出全部
		}
		Menu,extendedDict,Show
	}
}

ViewExtendDict(){
	Global extendedGui
	WinGetTitle, Title, ahk_id %extendedGui%
	if FileExist(Title:=RegExReplace(Title,"i)(?<=\w\.yaml).+")){
		GuiControl,extended:Enable,ViewExtendDict
		OpenAndSelect(Title)
	}
}

ReloadExtendDict(){
	Gui,extended:Default
	LV_Delete(),loadingListView()
}

AddItem(){
	Global extendedGui
	WinGetTitle, Title, ahk_id %extendedGui%
	if FileExist(Title:=RegExReplace(Title,"i)(?<=\w\.yaml).+")){
		if (Items:=SetParameterGui("扩展词格式：「纯词条、词条+Tab+Tab+词频、词条+Tab+编码+Tab+词频」",,,450,4,,"extended",extendedGui))&&WinExist("ahk_id" extendedGui){
			WinActivate,ahk_id %extendedGui%
			FileContent:=GetFileContent(Title,"UTF-8",1),extendedLongstring:="",Count:=0
			Loop,Parse,Items,`n,`r
			{
				if RegExReplace(A_LoopField,"^[\s\t]+|[\s\t]+$"){
					if objCount(tarr:=strSplit(RegExReplace(A_LoopField,"^[\s\t]+|[\s\t]+$"),"`t")){
						extendedString:=Trim(tarr[1] A_Tab tarr[2] A_Tab tarr[3])
						FileContent:=FileContent "`r`n"
						if Not FileContent~= "\r\n\s*" extendedString "[\s\t]*\r\n"&&tarr[1]{
							Gui,extended:Default
							LV_Add(LV_GetCount(),tarr[1],tarr[2],tarr[3])
							extendedLongstring.=extendedString "`r`n",Count++
						}
					}
				}
			}
			if extendedLongstring {
				FileRecycle,%Title%
				FileAppend,% RegExReplace(FileContent,"[\r\n]{2,}$","`r`n`r`n") . extendedLongstring,%Title%,UTF-8
				Traytip,小狼毫助手,% "操作成功，添加" Count "条" (objCount(tarr)-Count>0?"，重复" objCount(tarr)-Count "条。":"。"),,1
				ReloadWeasel()
			}Else
				Traytip,小狼毫助手,添加失败，词条已存在或为空！,,2
			SB_SetText("总计：" LV_GetCount() "行",2,"Center"),EmptyMem()
		}
	}
}

ExportAllextendCitiao(){
	Global extendedGui
	WinGetTitle, Title, ahk_id %extendedGui%
	if FileExist(Title:=RegExReplace(Title,"i)(?<=\w\.yaml).+")){
		Gui,extended:Default
		result:=""
		Loop,% LV_GetCount()
		{
			LV_GetText(citiao,A_Index,1),LV_GetText(bianma,A_Index,2),LV_GetText(cipin,A_Index,3)
			result.= citiao . A_Tab . bianma . ( cipin?A_Tab . cipin:"") "`r`n"
		}
		FileName:=RegExReplace(Title,".+\\|\..+") ".extend-" A_Now ".txt"
		if result {
			FileAppend,% Trim(result,"`r`n"),%A_Desktop%\%FileName%,UTF-8
			OpenAndSelect(A_Desktop "\" FileName)
		}
	}
}

CopyItem(){
	Global EventPos2
	if EventPos2 {
		Gui,extended:Default
		LV_GetText(citiao,EventPos2,1),LV_GetText(bianma,EventPos2,2),LV_GetText(cipin,EventPos2,3)
		Clipboard:= citiao . A_Tab . bianma . ( cipin?A_Tab . cipin:"")
	}
}

ShowExtendDict(){
	Global EventPos2
	if (A_GuiEvent="RightClick"){
		EventPos2:=A_EventInfo
	}else{
		Gui,extended:Default
		SB_SetText("总计：" LV_GetCount() "行",2,"Center")
	}
}

DeleteItem2(){
	Global EventPos2
	if EventPos2 {
		Gui,extended:Default
		LV_GetText(citiao,EventPos2,1),LV_GetText(bianma,EventPos2,2),LV_GetText(cipin,EventPos2,3)
		if DeleteItemFromFile([citiao,bianma,cipin]){
			LV_Delete(EventPos2)
			TrayTip,小狼毫助手,「%citiao%」删除成功，请手动部署生效！,,1
		}
		SB_SetText("总计：" LV_GetCount() "行",2,"Center")
	}
}

DeleteItemFromFile(obj){
	Global extendedGui
	WinGetTitle, Title, ahk_id %extendedGui%
	if FileExist(Title:=RegExReplace(Title,"i)(?<=\w\.yaml).+")){
		if FileContent:=GetFileContent(Title,"UTF-8",1){
			if (obj[1]&&obj[2]&&obj[3])
				all:= RegExReplace(FileContent "`r`n","\r\n\s*" obj[1] "\s*\t" obj[2] "\s*\t" obj[3] "[\s\t]*\r\n","`r`n`r`n`r`n")
			else if (obj[1]&&obj[2]&&!obj[3])
				all:= RegExReplace(FileContent "`r`n","\r\n\s*" obj[1] "\s*\t" obj[2] "[\s\t]*\r\n","`r`n`r`n`r`n")
			else if (obj[1]&&!obj[2]&&obj[3])
				all:= RegExReplace(FileContent "`r`n","\r\n\s*" obj[1] "\s*\t\s*\t" obj[3] "[\s\t]*\r\n","`r`n`r`n`r`n")
			else if (obj[1]&&!obj[2]&&!obj[3])
				all:= RegExReplace(FileContent "`r`n","\r\n\s*" obj[1] "[\s\t]*\r\n","`r`n`r`n`r`n")
			if (FileContent<>all&&!ErrorLevel) {
				FileRecycle,%Title%
				FileAppend,% all,%Title%,UTF-8
				Return 1
			}
		}
	}
}

FormatExtendDict(chars){
	if chars~="(\r\n[^\x00-\xff]+[^\t\r\n]*[^\x00-\xff]*\t\t\d+\r|\r\n[^\x00-\xff]+[^\t\r\n]*[^\x00-\xff]*(\t\w+)+|\r\n[^\x00-\xff]+[^\t\r\n]*[^\x00-\xff]*|\r\n[^\r\n\t\s\#]+\t\w+|\r\n[^\r\n\t\s\#]+\t\w+\t\d+)"{
		obj:={}
		Loop,Parse,chars,`n,`r
		{
			if RegExReplace(A_LoopField,"[\s\t]+$|^[\s\t]+")~="^\s*[^\r\n\s\t\#]+(\t\w+)+|^[^\x00-\xff]+[\s\t]*|^[^\x00-\xff]+\t\t\d+[\s\t]*"{
				tarr:=strSplit(RegExReplace(A_LoopField,"[\s\t]+$|^[\s\t]+"),"`t"),tarr[2]:=tarr[2]?tarr[2]:"",tarr[3]:=tarr[3]?tarr[3]:""
				if (objCount(obj[tarr[1]])&&obj[tarr[1],1]<>tarr[2])
					objPush(obj[tarr[1]],[tarr[2],tarr[3]])
				Else
					obj[tarr[1]]:=[[tarr[2],tarr[3]]]
			}
		}
		Return obj
	}
	Return {}
}

SyncToUserDir(){
	Global WeaselRoot
	if FileExist(WeaselRoot "\WeaselDeployer.exe"){
		traytip,, 正在同步用户资料以生成txt`n自造词词库记录，请稍候！,,1
		Command = "%WeaselRoot%\WeaselDeployer.exe" /sync
		Run *RunAs cmd.exe /c %Command%, , Hide
	}
}

ReloadWeasel(){
	global WeaselRoot,RimeUserDir
	if FileExist(WeaselRoot "\WeaselDeployer.exe"){
		FileRecycle,%RimeUserDir%\build\*.yaml
		For key,value In ["~","`%","`$","rime","``"]
			FileRecycle,%A_Temp%\%value%*.*
		Command = "%WeaselRoot%\WeaselDeployer.exe" /deploy
		Run *RunAs cmd.exe /c %Command%, , Hide
	}
}

ShowSchemaCizu(){
	Global EventPos
	if (A_GuiEvent="RightClick"){
		EventPos:=A_EventInfo
	}
}

RimeGuiContextMenu(GuiHwnd, CtrlHwnd, EventInfo, IsRightClick, X, Y){
	Global ServerExecutable,RimeUserDir,WeaselRoot
	if (IsRightClick&&A_GuiControl="ShowSchemaCizu"){
		Menu,UserDict,Deleteall
		Menu,UserDict,Add,刷新列表,ShowSchemaList
		Menu,UserDict,Add,
		Menu,UserDict,Add,复制词条,CopyUserItem
		Menu,UserDict,Add,
		Menu,UserDict,Add,导出全部,ExportAllCitiao
		Menu,UserDict,Add,
		Menu,UserDict,Add,删除词条,DeleteItem
		if (EventInfo&&LV_GetNext()) {
			Menu,UserDict,Enable,删除词条
			Menu,UserDict,Enable,导出全部
			Menu,UserDict,Enable,复制词条
		}else{
			Menu,UserDict,Disable,删除词条
			Menu,UserDict,Disable,导出全部
			Menu,UserDict,Disable,复制词条
		}
		Menu,UserDict,Show
	}else if (IsRightClick&&A_GuiControl="ShowSchemaList"){
		Menu,UserDict,Deleteall
		Menu,UserDict,Add,刷新方案列表,RefreshSchemaList
		Menu,UserDict,Add,
		Menu,UserDict,Add,启动算法服务,RefreshWeaselServer
		Menu,UserDict,Add,
		Menu,UserDict,Add,关闭算法服务,RefreshWeaselServer
		Process,Exist,%ServerExecutable%
		if ErrorLevel {
			Menu,UserDict,Disable,启动算法服务
		}else if (!ErrorLevel&&!FileExist(WeaselRoot "\" (ServerExecutable?ServerExecutable:"WeaselServer.exe"))){
			Menu,UserDict,Disable,启动算法服务
			Menu,UserDict,Disable,关闭算法服务
		}Else if (!ErrorLevel&&FileExist(WeaselRoot "\" (ServerExecutable?ServerExecutable:"WeaselServer.exe"))){
			Menu,UserDict,Disable,关闭算法服务
		}
		Menu,UserDict,Show
	}
}

RefreshSchemaList(){
	Global AllSchemaName
	if AllSchemaName:=GetSchemaList(){
		GuiControl,Rime:,ShowSchemaList,% "|" AllSchemaName
	}
}

RefreshWeaselServer(){
	Global ServerExecutable,RimeUserDir,WeaselRoot
	if FileExist(WeaselRoot "\" ServerExecutable){
		Process,Exist,%ServerExecutable%
		if ErrorLevel {
			Process,Close,%ServerExecutable%
			For key,value In ["~","`%","`$","rime","``","mpr"]
				FileDelete,%A_Temp%\%value%*.*
		}Else{
			For key,value In ["~","`%","`$","rime","``","mpr"]
				FileDelete,%A_Temp%\%value%*.*
			Run *RunAs "%WeaselRoot%\%ServerExecutable%" /restart
		}
	}
}

CopyUserItem(){
	Global EventPos
	if EventPos {
		Gui,Rime:Default
		LV_GetText(citiao,EventPos,1),LV_GetText(bianma,EventPos,2),LV_GetText(cipin,EventPos,3)
		Clipboard:= citiao . A_Tab . bianma . ( cipin?A_Tab . cipin:"")
	}
}

DeleteItem(){
	Global EventPos
	if EventPos {
		Gui,Rime:Default
		LV_Delete(EventPos)
	}
}

ShowSchemaList(){
	Global
	GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
	if objCount(FileLists)&&FileLists[ShowSchemaList]{
		if InStr(schemadictpath:=FileLists[ShowSchemaList],".src.dict."){
			if MainDictPath:=GetMainDictPath(schemadictpath){
				schemadictpath:= MainDictPath
			}Else{
				TrayTip,Error,词典文件路径获取失败！,,3
				Return
			}
		}
		SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
		name_no_ext:=RegExReplace(name_no_ext,"i)\.extended\.",".")
		ClassType:=GetDBClass(RegExReplace(name,"i)\.extended\.dict\.|\.dict\.",".schema.")),userdbfile:=""
		Switch ClassType
		{
			case "tabledb","stabledb":
				if FileExist(RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")){
					userdbfile:= RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")
				}
			case "userdb":
				installation:=GetFileContent(FileExist(RimeUserDir "\installation.yaml")?RimeUserDir "\installation.yaml":WeaselRoot "\data\installation.yaml")
				if RegExMatch(installation,"(?<=sync\_dir\:\s).+",sync_dir)&&RegExMatch(installation,"(?<=installation\_id\:\s).+",installation_id){
					sync_dir:=Trim(RegExReplace(sync_dir,"\\\\","\"),""""),installation_id:=Trim(installation_id,"""")
					if installationDir:=RegExReplace(sync_dir "\" installation_id,"\\\\","\"){
						if FileExist(RegExReplace(installationDir,"\\$") "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt"))
							userdbfile:= RegExReplace(installationDir,"\\$") "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")
					}
				}Else if InStr(installation,"installation_id:")&&!InStr(installation,"sync_dir:"){
					RegExMatch(installation,"(?<=installation\_id\:\s).+",installation_id)
					installation_id:=Trim(installation_id,"""")
					userdbfile:= RimeUserDir "\sync\" Trim(installation_id) "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")
				}
			case "plain_userdb":
				if FileExist(RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")){
					userdbfile:= RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")
				}
		}
		Gui,Rime:Default
		extendDict:= RegExReplace(name,"i)\.dict.",".src.dict.")
		if (!FileExist(RimeUserDir "\" extendDict)&&!FileExist(WeaselRoot "\data\" extendDict)){
			GuiControl,Rime:Disable,AddCitiao
		}Else{
			GuiControl,Rime:Enable,AddCitiao
		}
		LV_Delete()
		if FileExist(userdbfile){
			if objCount(UserDict:=GetUserdbList(userdbfile)) {
				Gui,Rime:Default
				for key,value in ["ExportDict1","ExportDict2","DeleteUserDict"]
				{
					if (ClassType="userdb"&&value="DeleteUserDict")
						GuiControl,Rime:Disable,%value%
					else
						GuiControl,Rime:Enable,%value%
				}
				for key,value in UserDict
				{
					LV_Add(A_Index,key,RegExReplace(value,"[^\w]"),1)
				}
			}Else{
				for key,value in ["ExportDict1","ExportDict2","DeleteUserDict"]
					GuiControl,Rime:Disable,%value%
			}
		}else{
			for key,value in ["ExportDict1","ExportDict2","DeleteUserDict"]
				GuiControl,Rime:Disable,%value%
		}
		EmptyMem()
	}
}

Getuserdbfilepath(){
	Global RimeUserDir,WeaselRoot,FileLists,schemadictpath,ClassType
	Gui,Rime:Default
	GuiControlGet,ShowSchemaList,,ShowSchemaList,ListBox
	if objCount(FileLists)&&FileLists[ShowSchemaList]{
		if InStr(schemadictpath:=FileLists[ShowSchemaList],".src.dict."){
			if MainDictPath:=GetMainDictPath(schemadictpath){
				schemadictpath:= MainDictPath
			}Else{
				TrayTip,Error,词典文件路径获取失败！,,3
				Return
			}
		}
		SplitPath, % schemadictpath, name, dir, ext, name_no_ext, drive
		ClassType:=GetDBClass(RegExReplace(name,"i)\.dict\.",".schema."))
		Switch ClassType
		{
			case "tabledb","stabledb":
				if FileExist(RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")){
					Return RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".txt")
				}
			case "userdb":
				installation:=GetFileContent(FileExist(RimeUserDir "\installation.yaml")?RimeUserDir "\installation.yaml":RimeUserDir "\build\installation.yaml")
				if RegExMatch(installation,"(?<=sync\_dir\:\s).+",sync_dir)&&RegExMatch(installation,"(?<=installation\_id\:\s).+",installation_id){
					sync_dir:=Trim(RegExReplace(sync_dir,"\\\\","\"),""""),installation_id:=Trim(installation_id,"""")
					if installationDir:=RegExReplace(sync_dir "\" installation_id,"\\\\","\"){
						if FileExist(RegExReplace(installationDir,"\\$") "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt"))
							Return RegExReplace(installationDir,"\\$") "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")
					}
				}
			case "plain_userdb":
				if FileExist(RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")){
					Return RimeUserDir "\" RegExReplace(name_no_ext,"i)\.dict$",".userdb.txt")
				}
		}
	}
}

GetDBClass(FileName){
	Global WeaselRoot,InstallDir,RimeUserDir,FileLists
	RegExMatch(GetFileContent(RimeUserDir "\build\" FileName),"(?<=[\s]db\_class\:\s).+",db_class)

	Return db_class
}

GetUserdbList(FilePath){
	Contents:=GetFileContent(FilePath),obj:={}
	Loop,Parse,Contents, `n, `r
	{
		if InStr(A_LoopField,"enc"){
			tarr:=strSplit(A_LoopField,"`t")
			if (tarr[1]~="[^\x00-\xff]"&&InStr(tarr[2],"enc")&&StrLen(tarr[2])>7){
				if (!obj[tarr[1]]||StrLen(tarr[2])>StrLen(obj[tarr[1]])){
					obj[tarr[1]]:=SubStr(tarr[2],-3)
				}
			}else if (tarr[2]~="[^\x00-\xff]"&&InStr(tarr[1],"enc")&&StrLen(tarr[1])>7){
				if (!obj[tarr[2]]||StrLen(tarr[1])>StrLen(obj[tarr[2]])){
					obj[tarr[2]]:=SubStr(tarr[1],-3)
				}
			}
		}
	}

	Return obj
}

GetSchemaList(flag:=0){
	Global FileLists,RimeUserDir,WeaselRoot
	schemalist:="",FileLists:={}
	Loop,Files,%RimeUserDir%\build\*.schema.yaml
	{
		if RegExMatch(FileContent:=GetFileContent(A_LoopFileFullPath),"(?<=[\s\t]name\:\s)\s*[^\t\r\n]+",schemaName){
			schemalist.="|" Trim(schemaName,"""")
			if RegExMatch(FileContent,"(?<=[\s\t]dictionary\:\s)\s*\w+",dictionary,InStr(FileContent,"`ntranslator:")){
				FileLists[Trim(schemaName,"""")]:=FileExist(RimeUserDir "\" Trim(dictionary,"""") ".dict.yaml")?RimeUserDir "\" Trim(dictionary,"""") ".dict.yaml":WeaselRoot "\data\" Trim(dictionary,"""") ".dict.yaml"
			}
		}
	}
	Return Trim(schemalist,"|")
}

GetFileContent(FilePath,Encoding="UTF-8",Recycle:=0){
	If FileExist(FilePath){
		FileEncoding,%Encoding%
		FileRead,chars,%FilePath%
		chars:=RegExReplace(RegExReplace(RegExReplace(chars,"`r`n","`r"),"`n","`r"),"`r","`r`n")
		if !Recycle {
			chars:=RegExReplace(RegExReplace(chars,"`r`n[\s\t]+`r`n","`r`n"),"(*BSR_ANYCRLF)\R+", "`r`n")
		}

		return Trim(chars)
	}
}

OnReload(){
	Reload
}


OnExits(){
	ExitApp
}

;;;根据进程文件名获取托盘图标信息列表，以判断托盘图标是否正常显示
TrayIcon_GetInfo(sExeName := "")
{
	d := A_DetectHiddenWindows
	DetectHiddenWindows, On
 
	oTrayInfo := []
	For key,sTray in ["Shell_TrayWnd", "NotifyIconOverflowWindow"]
	{
		idxTB := TrayIcon_GetTrayBar(sTray)
		WinGet, pidTaskbar, PID, ahk_class %sTray%
		
		hProc := DllCall("OpenProcess",	UInt,0x38, Int,0, UInt,pidTaskbar)
		pRB   := DllCall("VirtualAllocEx", Ptr,hProc, Ptr,0, UPtr,20, UInt,0x1000, UInt,0x04)
 
		szBtn := VarSetCapacity(btn, (A_Is64bitOS ? 32 : 20), 0)
		szNfo := VarSetCapacity(nfo, (A_Is64bitOS ? 32 : 24), 0)
		szTip := VarSetCapacity(tip, 128 * 2, 0)
 
		; TB_BUTTONCOUNT = 0x0418
		SendMessage, 0x0418, 0, 0, ToolbarWindow32%idxTB%, ahk_class %sTray%
		Loop, %ErrorLevel%
		{
			 ; TB_GETBUTTON 0x0417
			SendMessage, 0x0417, A_Index-1, pRB, ToolbarWindow32%idxTB%, ahk_class %sTray%
 
			DllCall("ReadProcessMemory", Ptr,hProc, Ptr,pRB, Ptr,&btn, UPtr,szBtn, UPtr,0)
 
			iBitmap := NumGet(btn, 0, "Int")
			idCmd   := NumGet(btn, 4, "Int")
			fsState := NumGet(btn, 8, "UChar")
			fsStyle := NumGet(btn, 9, "UChar")
			dwData  := NumGet(btn, (A_Is64bitOS ? 16 : 12), "UPtr")
			iString := NumGet(btn, (A_Is64bitOS ? 24 : 16), "Ptr")
 
			DllCall("ReadProcessMemory", Ptr,hProc, Ptr,dwData, Ptr,&nfo, UPtr,szNfo, UPtr,0)
 
			hWnd  := NumGet(nfo, 0, "Ptr")
			uId   := NumGet(nfo, (A_Is64bitOS ?  8 :  4), "UInt")
			msgId := NumGet(nfo, (A_Is64bitOS ? 12 :  8), "UPtr")
			hIcon := NumGet(nfo, (A_Is64bitOS ? 24 : 20), "Ptr")
 
			WinGet, nPid, PID, ahk_id %hWnd%
			WinGet, sProcess, ProcessName, ahk_id %hWnd%
			WinGetClass, sClass, ahk_id %hWnd%
 
			If ( !sExeName || sExeName == sProcess || sExeName == nPid )
			{
				DllCall("ReadProcessMemory", Ptr,hProc, Ptr,iString, Ptr,&tip, UPtr,szTip, UPtr,0)
				oTrayInfo.Push({ "idx"	 : A_Index-1
							   , "idcmd"   : idCmd
							   , "pid"	 : nPid
							   , "uid"	 : uId
							   , "msgid"   : msgId
							   , "hicon"   : hIcon
							   , "hwnd"	: hWnd
							   , "class"   : sClass
							   , "process" : sProcess
							   , "tooltip" : StrGet(&tip, "UTF-16")
							   , "tray"	: sTray })
			}
		}
		DllCall("VirtualFreeEx", Ptr,hProc, Ptr,pRB, UPtr,0, UInt,0x8000)
		DllCall("CloseHandle",   Ptr,hProc)
	}
	DetectHiddenWindows, %d%
	Return oTrayInfo
}

TrayIcon_GetTrayBar(sTray:="Shell_TrayWnd")
{
	d := A_DetectHiddenWindows
	DetectHiddenWindows, On
	WinGet, ControlList, ControlList, ahk_class %sTray%
	RegExMatch(ControlList, "(?<=ToolbarWindow32)\d+(?!.*ToolbarWindow32)", nTB)
	Loop, %nTB%
	{
		ControlGet, hWnd, hWnd,, ToolbarWindow32%A_Index%, ahk_class %sTray%
		hParent := DllCall( "GetParent", Ptr, hWnd )
		WinGetClass, sClass, ahk_id %hParent%
		If !(sClass == "SysPager" || sClass == "NotifyIconOverflowWindow" )
			Continue
		idxTB := A_Index
		Break
	}
	DetectHiddenWindows, %d%
	Return idxTB
}
;;根据进程文件名获取进程信息列表
GetProcessNameList(ProcessName:=""){
	list:="",tarr:=[]
	s := 10240  ; 缓存和数组的大小(4 KB)

	Process, Exist  ; 设置 ErrorLevel 为这个正在运行脚本的 PID.
	; 使用 PROCESS_QUERY_INFORMATION(0x0400) 获取此脚本的句柄:
	h := DllCall("OpenProcess", "UInt", 0x0400, "Int", false, "UInt", ErrorLevel, "Ptr")
	; 打开此进程的可调整的访问令牌(TOKEN_ADJUST_PRIVILEGES = 32):
	DllCall("Advapi32.dll\OpenProcessToken", "Ptr", h, "UInt", 32, "PtrP", t)
	VarSetCapacity(ti, 16, 0)  ; 特权结构
	NumPut(1, ti, 0, "UInt")  ; 特权数组中的一个条目...
	; 获取调试特权的本地唯一标识符:
	DllCall("Advapi32.dll\LookupPrivilegeValue", "Ptr", 0, "Str", "SeDebugPrivilege", "Int64P", luid)
	NumPut(luid, ti, 4, "Int64")
	NumPut(2, ti, 12, "UInt")  ; 启用这个特权: SE_PRIVILEGE_ENABLED = 2
	; 使用新的访问令牌更新此进程的特权:
	r := DllCall("Advapi32.dll\AdjustTokenPrivileges", "Ptr", t, "Int", false, "Ptr", &ti, "UInt", 0, "Ptr", 0, "Ptr", 0)
	DllCall("CloseHandle", "Ptr", t)  ; 关闭此访问令牌句柄以节约内存.
	DllCall("CloseHandle", "Ptr", h)  ; 关闭此进程句柄以节约内存.

	hModule := DllCall("LoadLibrary", "Str", "Psapi.dll")  ; 通过预加载来提升性能.
	s := VarSetCapacity(a, s)  ; 接收进程列表标识符的数组:

	DllCall("Psapi.dll\EnumProcesses", "Ptr", &a, "UInt", s, "UIntP", r)
	Loop, % r // 4  ; 把数组解析为 DWORD(32 位) 的标识符:
	{
		id := NumGet(a, A_Index * 4, "UInt")
		; 打开进程: PROCESS_VM_READ(0x0010) | PROCESS_QUERY_INFORMATION(0x0400)
		h := DllCall("OpenProcess", "UInt", 0x0010 | 0x0400, "Int", false, "UInt", id, "Ptr")
		if !h
			continue
		VarSetCapacity(n, s, 0)  ; 接收模块基础名称的缓存:
		e := DllCall("Psapi.dll\GetModuleBaseName", "Ptr", h, "Ptr", 0, "Str", n, "UInt", A_IsUnicode ? s//2 : s)
		if !e    ;  用于 64 位进程在 32 位模式时的回退方法:
			if e := DllCall("Psapi.dll\GetProcessImageFileName", "Ptr", h, "Str", n, "UInt", A_IsUnicode ? s//2 : s)
				SplitPath n, n
		DllCall("CloseHandle", "Ptr", h)  ; 关闭进程句柄以节约内存
		if (n && e){  ; 如果映像不是空的, 则添加到列表:
			If (ProcessName&&ProcessName=n)
				tarr.push([n,id])
			else
				list.=n "/" id "|"
		}
	}
	DllCall("FreeLibrary", "Ptr", hModule)  ; 卸载库来释放内存.

	return !ProcessName?list:tarr
}

EmptyMem(PID=""){
	pid:=!PID ? DllCall("GetCurrentProcessId") : pid
	h:=DllCall("OpenProcess", "UInt", 0x001F0FFF, "Int", 0, "Int", pid)
	DllCall("SetProcessWorkingSetSize", "UInt", h, "Int", -1, "Int", -1)
	DllCall("CloseHandle", "Int", h)
}

TrayRefresh() {
/*		Remove any dead icon from the tray menu
 *		Should work both for W7 & W10
 */
	WM_MOUSEMOVE := 0x200
	detectHiddenWin := A_DetectHiddenWindows
	DetectHiddenWindows, On
	allTitles := ["ahk_class Shell_TrayWnd"
			, "ahk_class NotifyIconOverflowWindow"]
	allControls := ["ToolbarWindow321"
				,"ToolbarWindow322"
				,"ToolbarWindow323"
				,"ToolbarWindow324"]
	allIconSizes := [24,32]

	for id, title in allTitles {
		for id, controlName in allControls
		{
			for id, iconSize in allIconSizes
			{
				ControlGetPos, xTray,yTray,wdTray,htTray,% controlName,% title
				y := htTray - 10
				While (y > 0)
				{
					x := wdTray - iconSize/2
					While (x > 0)
					{
						point := (y << 16) + x
						PostMessage,% WM_MOUSEMOVE, 0,% point,% controlName,% title
						x -= iconSize/2
					}
					y -= iconSize/2
				}
			}
		}
	}
	DetectHiddenWindows, %detectHiddenWin%
}

GetDefaultFontName(){
	NumPut(VarSetCapacity(info, A_IsUnicode ? 504 : 344, 0), info, 0, "UInt")
	DllCall("SystemParametersInfo", "UInt", 0x29, "UInt", 0, "Ptr", &info, "UInt", 0)
	return StrGet(&info + 52)
}

;图片base64转化为正常图片
Base64Toimage(Base64,outfilepath){
	Local Bytes := 0,Len := StrLen(Base64)
	DllCall( "Crypt32.dll\CryptStringToBinary", "Str",Base64, "UInt",Len, "UInt",0x1, "UInt",0, "UIntP",Bytes, "Int",0, "Int",0 )	; CRYPT_STRING_BASE64 := 0x1
	VarSetCapacity( Bin, 128 ), VarSetCapacity( Bin, 0 ), VarSetCapacity( Bin, Bytes, 0 )
	DllCall( "Crypt32.dll\CryptStringToBinary", "Str",Base64, "UInt",Len, "UInt",0x1, "Ptr",&Bin, "UIntP",Bytes, "Int",0, "Int",0 )
	File := FileOpen(outfilepath, "w")
	File.RawWrite(Bin, Bytes)
	File.Close()
}

OpenAndSelect(sFullPath){
	SplitPath sFullPath, , sPath, ext, name_no_ext
	FolderPidl := DllCall("shell32\ILCreateFromPath", "Str", sPath)
	DllCall("shell32\SHParseDisplayName", "str", sFullPath, "Ptr", 0, "Ptr*", ItemPidl := 0, "Uint", 0, "Uint*", 0)
	DllCall("shell32\SHOpenFolderAndSelectItems", "Ptr", FolderPidl, "UInt", 1, "Ptr*", ItemPidl, "Int", 0)
	CoTaskMemFree(FolderPidl)
	if name_no_ext
		CoTaskMemFree(ItemPidl)
}

CoTaskMemFree(pv) {
	Return DllCall("ole32\CoTaskMemFree", "Ptr", pv)
}

SetParameterGui(Title:="InputBox",TipText:="", IsNumber=0, Width:=250,Row=2,NoOwner=0,Owner:="",GHWND:=0){
	static
	ButtonOK:=ButtonCancel:= false,IsNumber:=IsNumber=1?" Number ":"",O:=NoOwner?" +Owner -SysMenu":""
	,flag:=0,wpos:=0,hpos:=0,IsLightTheme:=A_HOUR>5&&A_HOUR<19?1:0
	SysGet, CXVSCROLL, 2
	SysGet, SM_CYSIZE, 31
	SysGet,SM_CYSIZEFRAME ,33
	Gui, InputBox:Destroy
	If Owner
		Gui, InputBox:+Owner%Owner%
	Gui, InputBox: %O%  +Resize -MaximizeBox +LastFound -MinimizeBox hWndsInputBox
	Gui,InputBox:Color,% !IsLightTheme?"0x333333":"0xffffff",% !IsLightTheme?"0x333333":"0xf0f0f0"
	Gui, InputBox:Font,% "s10 norm " (!IsLightTheme?"cCDCDCD":"Default"), % GetDefaultFontName()
	Gui, InputBox: add, Edit,x15 y15 r%Row%  w%Width% %IsNumber% vInputBox hwndIBox WantTab +Wrap,% Row>1?TipText:""
	Gui, InputBox: add, Button, w60 gInputBoxOK vInputBoxOK HWNDBTNT8, &确定
	GuiControlGet, ibox, Pos , InputBoxOK
	xpos:=Width-45
	Gui, InputBox: add, Button, w60 x%xpos% yp gInputBoxCancel HWNDBTNT9, &取消
	If (Row=1)
		EM_SetCueBanner(IBox, TipText)
	Gui, InputBox:Font,% "s9 norm " (!IsLightTheme?"cCDCDCD":"Default"), % GetDefaultFontName()
	Gui, InputBox:Add,StatusBar,% !IsLightTheme?"BackgroundCDCDCD -Theme ":"BackgroundDefault -Theme ",>>窗口边缘可以调节窗口大小。
	Gui, InputBox: Show,AutoSize, % Title
	if !NoOwner
		Gui, InputBox: -AlwaysOnTop
	SendMessage, 0xB1, 0, -1, Edit1, A
	ControlFocus , Edit1, A
	while !(ButtonOK||ButtonCancel){
		if (!WinExist("ahk_id " GHWND)&&GHWND){
			Gui, InputBox:Destroy
		}Else{
			continue
		}
	}
	if (ButtonCancel) {
		return
	}
	Gui, InputBox: Submit, NoHide
	Gui, InputBox: Cancel
	Gui, InputBox:Destroy
	flag:=0
	return InputBox

	InputBoxOK:
		ButtonOK:= true
	return

	InputBoxGuiSize:
		If !flag {
			flag:=1
			Gui, InputBox:+MinSize%A_GuiWidth%x%A_GuiHeight%
		}else{
			ControlGetPos , X_button, Y_button, W_button, H_button, Button1
			ControlGetPos , X_Edit, Y_Edit, Width, Height, Edit1
			GuiControl, InputBox:move, Edit1 , % "w" A_GuiWidth-(X_Edit-8)-SM_CYSIZEFRAME*(A_ScreenDPI/96) " h" A_GuiHeight-(Y_Edit-SM_CYSIZE*(A_ScreenDPI/96))*2-H_button
			GuiControl, InputBox:move, Button1 , % "y" A_GuiHeight-(Y_Edit-SM_CYSIZE*(A_ScreenDPI/96))-H_button
			GuiControl, InputBox:move, Button2 , % "y" A_GuiHeight-(Y_Edit-SM_CYSIZE*(A_ScreenDPI/96))-H_button "x" A_GuiWidth-(X_Edit-8+W_button)//(A_ScreenDPI/96)
			GuiControl,InputBox:,Button2,取消
			GuiControl,InputBox:,Button1,确定
		}
		wpos:= A_GuiWidth ,hpos:= A_GuiHeight,SB_SetParts(A_GuiWidth*0.75,A_GuiWidth*0.25)
	return

	InputBoxGuiClose:
	InputBoxGuiEscape:
	InputBoxCancel:
		ButtonCancel:= true,flag:=0
		Gui, InputBox: Cancel
		Gui, InputBox:Destroy
	return
}

;获取指定位置坐标色值
GetCursorColor(x:="",y:="",w:=1,h:=1){ ;取色
	static pt
	pt?"":(DllCall("GetModuleHandle","str","gdiplus","UPtr"),VarSetCapacity(i,A_PtrSize=8?24:16,0),i:=Chr(1)
		,DllCall("gdiplus\GdiplusStartup","UPtr*",pt,"UPtr",&i,"UPtr",0))
	,(x="")?GetCursorPos(x,y):""
	,d:=DllCall("CreateCompatibleDC","Uint",0),VarSetCapacity(b,40,0),NumPut(w,b,4,"uint")
	,NumPut(h,b,8,"uint"),NumPut(40,b,0,"uint"),NumPut(1,b,12,"ushort"),NumPut(0,b,16,"uInt"),NumPut(32,b,14,"ushort")
	,m:=DllCall("CreateDIBSection","UPtr",d,"UPtr",&b,"uint",0,"UPtr*",0,"UPtr",0,"uint",0,"UPtr")
	,o:=DllCall("SelectObject","UPtr",d,"UPtr",m)
	,DllCall("BitBlt","UPtr",d,"int",0,"int",0,"int",w,"int",h,"UPtr",i:=DllCall("GetDC","UPtr",0),"int",x,"int",y,"uint",0x00CC0020)
	,DllCall("ReleaseDC","UPtr",0,"UPtr",i)
	,DllCall("gdiplus\GdipCreateBitmapFromHBITMAP","UPtr",m,"UPtr",Palette,"UPtr*",p)
	,DllCall("SelectObject","UPtr",d,"UPtr",o),DllCall("DeleteObject","UPtr",m)
	,DllCall("DeleteDC","UPtr",i),DllCall("DeleteDC","UPtr",d),VarSetCapacity(t,16)
	,NumPut(0,t,0,"uint"),NumPut(0,t,4,"uint"),NumPut(w,t,8,"uint"),NumPut(h,t,12,"uint")
	,VarSetCapacity(b,16+2*A_PtrSize,0),DllCall("Gdiplus\GdipBitmapLockBits","UPtr",p,"UPtr",&t,"uint",3,"int",0x26200a,"UPtr",&b)
	,e:= NumGet(b,8,"Int"),u:=NumGet(b,16,"UPtr"),r:=A_FormatInteger
	SetFormat,IntegerFast,hex
	if (w>1 or h>1)
	{
		f:=[]
		Loop,%h%
		{
			f[A_Index]:=j:=[],s:=(A_Index-1)*e
			Loop,%w%
				j[A_Index]:=NumGet(u+0,((A_Index-1)*4)+s,"UInt")  & 0x00ffffff ""
		}
	}
	else f:=NumGet(u+0,0,"UInt") & 0x00ffffff  ""
	SetFormat,IntegerFast,%r%
	DllCall("Gdiplus\GdipBitmapUnlockBits","UPtr",p,"UPtr",0)
	DllCall("gdiplus\GdipDisposeImage", "uint", p)
	return f
}
;获取鼠标所在位置坐标
GetCursorPos(byref x,byref y){
	static i:=VarSetCapacity(i,8,0)
	DllCall("GetCursorPos","Ptr",&i),X:=NumGet(i,0,"Int"),y:=NumGet(i,4,"Int")
}

;;色值格式化为ARGB
FormatColor(Color){
	if Not Color~="i)^\d+$|0x[a-fA-F0-9]{3,6}"
		Return "0xff000000"
	Return Format("0xff{:06x}",Color)
}

;色值深浅色判断
GetgrayLevel(Color){
	HEX:=HexToRGB(Color,"Parse"),arr:=strsplit(HEX,",")
	If (objCount(arr)>2)
		Return arr[1] * 0.299 + arr[2] * 0.587 + arr[3] * 0.114
	Return 0
}

HexToRGB(Color, Mode="") ; Input: 6 characters HEX-color. Mode can be RGB, Message (R: x, G: y, B: z) or parse (R,G,B)
{
	; If df, d is *16 and f is *1. Thus, Rx = R*16 while Rn = R*1
	Color:=regexreplace(Color,"^(0x|0X|#)")
	Rx := SubStr(Color, 1,1), Rn := SubStr(Color, 2,1)
	Gx := SubStr(Color, 3,1), Gn := SubStr(Color, 4,1)
	Bx := SubStr(Color, 5,1), Bn := SubStr(Color, 6,1)
	AllVars := "Rx|Rn|Gx|Gn|Bx|Bn"
	Loop, Parse, Allvars, | ; Add the Hex values (A - F)
	{
		StringReplace, %A_LoopField%, %A_LoopField%, a, 10
		StringReplace, %A_LoopField%, %A_LoopField%, b, 11
		StringReplace, %A_LoopField%, %A_LoopField%, c, 12
		StringReplace, %A_LoopField%, %A_LoopField%, d, 13
		StringReplace, %A_LoopField%, %A_LoopField%, e, 14
		StringReplace, %A_LoopField%, %A_LoopField%, f, 15
	}
	R := Rx*16+Rn, G := Gx*16+Gn, B := Bx*16+Bn
	If (Mode = "Message") ; Returns "R: 255 G: 255 B: 255"
		Out := "R:" . R . " G:" . G . " B:" . B
	else if (Mode = "Parse") ; Returns "255,255,255"
		Out := R . "," . G . "," . B
	else
		Out := R . G . B ; Returns 255255255
	return Out
}

EM_SetCueBanner(hWnd, Cue)
{
	static EM_SETCUEBANNER := 0x1501
	return DllCall("User32.dll\SendMessage", "Ptr", hWnd, "UInt", EM_SETCUEBANNER, "Ptr", True, "WStr", Cue)
}

GetProcessFullPath(p_id) {
	for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process where ProcessId=" p_id)
		return process.ExecutablePath
}

ProcessGetBits(vPID){   ;;获取进程位数
	if !A_Is64bitOS
		Return 86

	hProc := DllCall("kernel32\OpenProcess", UInt,0x400, Int,0, UInt,vPID, Ptr)
	DllCall("kernel32\IsWow64Process", Ptr,hProc, IntP,vIsWow64Process)
	DllCall("kernel32\CloseHandle", Ptr,hProc)

	if vIsWow64Process
		Return 86

	Return 64
}

;;根据指定进程文件名获取进程信息
GetProcessInfo(exename,type:="ExecutablePath") {
	/*
	class Win32_Process : CIM_Process
	{
		string   CreationClassName;	创建类的名称
		string   Caption;	进程标题
		string   CommandLine;	进程的命令行
		datetime CreationDate;	创建日期
		string   CSCreationClassName;
		string   CSName;
		string   Description;	显示进程说明
		string   ExecutablePath;	可执行路径
		uint16   ExecutionState;	执行状态
		string   Handle;	句柄
		uint32   HandleCount;	句柄统计
		datetime InstallDate;	安装日期
		uint64   KernelModeTime;	内核调节时间
		uint32   MaximumWorkingSetSize;
		uint32   MinimumWorkingSetSize;
		string   Name;	进程名
		string   OSCreationClassName;	系统创建类名
		string   OSName;	系统名
		uint64   OtherOperationCount;
		uint64   OtherTransferCount;
		uint32   PageFaults;	页面默认值
		uint32   PageFileUsage;
		uint32   ParentProcessId;
		uint32   PeakPageFileUsage;
		uint64   PeakVirtualSize;
		uint32   PeakWorkingSetSize;
		uint32   Priority = NULL;
		uint64   PrivatePageCount;
		uint32   ProcessId;	进程ID
		uint32   QuotaNonPagedPoolUsage;
		uint32   QuotaPagedPoolUsage;
		uint32   QuotaPeakNonPagedPoolUsage;
		uint32   QuotaPeakPagedPoolUsage;
		uint64   ReadOperationCount;
		uint64   ReadTransferCount;
		uint32   SessionId;	会话的唯一标识符
		string   Status;	状态值
		datetime TerminationDate;	终止日期
		uint32   ThreadCount;	线程计数
		uint64   UserModeTime;	用户模式时间
		uint64   VirtualSize;	虚拟化大小
		string   WindowsVersion;
		uint64   WorkingSetSize;
		uint64   WriteOperationCount;
		uint64   WriteTransferCount;
	};
	*/
	for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process where name ='" exename "'")
		return process[type]
}

/*
	FileDescription	文件描述说明
	FileVersion	文件版本
	InternalName	内部名称
	LegalCopyright	法律版权所有
	OriginalFilename	创建文件时所使用的名称
	ProductName	产品名称
	ProductVersion	产品版本
	CompanyName	企业名称
	PrivateBuild	私有版本的信息
	SpecialBuild	特殊内部版本信息
	LegalTrademarks	文件的商标和注册商标
*/
;;获取文件信息
FileGetInfo(FilePath:="", p*) {   ; Written by SKAN, modified by HotKeyIt	; www.autohotkey.com/forum/viewtopic.php?p=233188#233188  CD:24-Nov-2008 / LM:27-Oct-2010
	static DLL:="Version\GetFileVersion"
	If ! FSz := DllCall( DLL "InfoSize" (A_IsUnicode ? "W" : "A"), "Str",FilePath, "UInt",0 )
		Return DllCall( "SetLastError", UInt,1 ),""
	VarSetCapacity( FVI, FSz, 0 ),DllCall( DLL "Info" ( A_IsUnicode ? "W" : "A"), "Str",FilePath, "UInt",0, "UInt",FSz, "PTR",&FVI )
	If !DllCall( "Version\VerQueryValue" (A_IsUnicode ? "W" : "A"), "PTR",&FVI, "Str","\VarFileInfo\Translation", "PTR*",Transl, "PTR",0 )
		Return DllCall( "SetLastError", UInt,2 ),""
	If !Trans:=format("{1:.8X}",NumGet(Transl+0,"UInt"))
		Return DllCall( "SetLastError", UInt,3),""
	for k,v in p
	{
		subBlock := "\StringFileInfo\" SubStr(Trans,-3) SubStr(Trans,1,4) "\" v
		If ! DllCall( "Version\VerQueryValue" ( A_IsUnicode ? "W" : "A"), "PTR",&FVI, "Str",SubBlock, "PTR*",InfoPtr, "UInt",0 )
			continue
		If Value := StrGet( InfoPtr )
			Info .= p.MaxIndex()=1?Value:SubStr( v "                        ",1,24 ) . A_Tab . Value . "`n"
	}
	Info:=RTrim(Info,"`n")

	Return Info
}

;自定义MsgBox按钮名称
MsgBoxRenBtn(WinTitle="",btn1="",btn2="",btn3=""){
	Static sbtn1:="", sbtn2:="", sbtn3:="", i=0
	sbtn1 := btn1, sbtn2 := btn2, sbtn3 := btn3, i=0
	SetTimer, MsgBoxRenBtn, 100
	Return

	MsgBoxRenBtn:
		If (hwnd:=WinTitle?WinExist(WinTitle):WinActive("ahk_class #32770")) {
			if (sbtn1)
				ControlSetText, Button1, % sbtn1, ahk_id %hwnd%
			if (sbtn2)
				ControlSetText, Button2, % sbtn2, ahk_id %hwnd%
			if (sbtn3)
				ControlSetText, Button3, % sbtn3, ahk_id %hwnd%
			SetTimer, MsgBoxRenBtn, Off
		}else{
			SetTimer, MsgBoxRenBtn, Off
		}
		if (i >= 5000)
			SetTimer, MsgBoxRenBtn, Off
		i++
	Return
}

WaitComboKey(Options:=""){
	InputHook := InputHook(Options)
	if !InStr(Options, "V")
		InputHook.VisibleNonText := false
	InputHook.KeyOpt("{All}", "E")  ; 结束
	; Exclude the modifiers
	InputHook.KeyOpt("{LCtrl}{RCtrl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}", "-E")
	InputHook.Start()
	ErrorLevel := InputHook.Wait()  ; 将 EndReason 存储在 ErrorLevel 中
	return InputHook.EndMods . InputHook.EndKey  ; 返回字符串 如 <^<+Esc
}
Tray_Refresh() {
/*		Remove any dead icon from the tray menu
 *		Should work both for W7 & W10
 */
	WM_MOUSEMOVE := 0x200
	detectHiddenWin := A_DetectHiddenWindows
	DetectHiddenWindows, On
	allTitles := ["ahk_class Shell_TrayWnd"
			, "ahk_class NotifyIconOverflowWindow"]
	allControls := ["ToolbarWindow321"
				,"ToolbarWindow322"
				,"ToolbarWindow323"
				,"ToolbarWindow324"]
	allIconSizes := [24,32]

	for id, title in allTitles {
		for id, controlName in allControls
		{
			for id, iconSize in allIconSizes
			{
				ControlGetPos, xTray,yTray,wdTray,htTray,% controlName,% title
				y := htTray - 10
				While (y > 0)
				{
					x := wdTray - iconSize/2
					While (x > 0)
					{
						point := (y << 16) + x
						PostMessage,% WM_MOUSEMOVE, 0,% point,% controlName,% title
						x -= iconSize/2
					}
					y -= iconSize/2
				}
			}
		}
	}

	DetectHiddenWindows, %detectHiddenWin%
}
;获取系统计划任务自启列表
GetTaskInfos() {
	objService := ComObjCreate("Schedule.Service")
	objService.Connect()
	rootFolder := objService.GetFolder("\")
	taskCollection := rootFolder.GetTasks(0)
	numberOfTasks := taskCollection.Count
	; ?RegistrationInfo.Author
	For registeredTask, state in taskCollection
	{
		if (registeredTask.state == 0)
			state:= "Unknown"
		else if (registeredTask.state == 1)
			state:= "Disabled"
		else if (registeredTask.state == 2)
			state:= "Queued"
		else if (registeredTask.state == 3)
			state:= "Ready"
		else if (registeredTask.state == 4)
			state:= "Running"
		tasklist .= registeredTask.Name "=" state "=" registeredTask.state "`n"
	}
	return RTrim(tasklist,"`n")
}
;判断是否自启
IsAutorunEnabled(TaskName)
{
	objService := ComObjCreate("Schedule.Service") 
	objService.Connect()
	objFolder := objService.GetFolder("\")
	Try {
		RunAsTask := objFolder.GetTask( TaskName )
		return  ! A_LastError 
	}Catch
		Return ""
}
;取消自启
DisableAutorun(TaskName){
	objService := ComObjCreate("Schedule.Service") 
	objService.Connect()
	objFolder := objService.GetFolder("\")
	Try {
		objFolder.DeleteTask(TaskName, 0)
		Return !A_LastError
	}Catch
		Return ""
}
;根据自启任务名获取自启文件长路径
GetTaskActionExecPaths(taskName, folderPath := "\") {
	service := ComObjCreate("Schedule.Service")
	service.Connect()
	Try {
		Paths:=[]
		for action in service.GetFolder(folderPath).GetTask(taskName).Definition.Actions
			if (action.Type ==0)
				Paths.Push([RegExReplace(action.Path,"[\""""]"),RegExReplace(action.Arguments,"[\""""]")])
		Return Paths
	}Catch
		Return []
}
;设置自启
EnableAutoRun(taskName:="",DescriptionInfo:="",ProcessPath="",ScriptPath="",TaskState=3)
{
	if (!TaskName||!ProcessPath)
		Return -1
	TaskExists := IsAutorunEnabled(taskName)
	if (A_IsAdmin and TaskExists) {
		if DisableAutorun(TaskName)
			Return 1
	}else If ( not A_IsAdmin and TaskExists ) {
		Return ""
	}else If ( not A_IsAdmin and not TaskExists ){
		Return ""
	}else If ( A_IsAdmin and not TaskExists ) {
		TriggerType = 9   ; trigger on logon. 
		ActionTypeExec = 0  ; specifies an executable action. 
		TaskCreateOrUpdate = 6 
		Task_Runlevel_Highest = 1 

		objService := ComObjCreate("Schedule.Service") 
		objService.Connect() 

		objFolder := objService.GetFolder("\") 
		objTaskDefinition := objService.NewTask(0) 

		principal := objTaskDefinition.Principal 
		principal.LogonType := 1    ; Set the logon type to TASK_LOGON_PASSWORD 
		principal.RunLevel := Task_Runlevel_Highest  ; Tasks will be run with the highest privileges. 

		colTasks := objTaskDefinition.Triggers 
		objTrigger := colTasks.Create(TriggerType) 
		colActions := objTaskDefinition.Actions 
		objAction := colActions.Create(ActionTypeExec) 
		objAction.ID := "Autorun" 
		if(A_IsCompiled)
			objAction.Path := """" Trim(ProcessPath) """"
		else
		{
			objAction.Path := """" Trim(ProcessPath) """"
			objAction.Arguments := """" Trim(ScriptPath) """"
		}
		objAction.WorkingDirectory := A_ScriptDir
		objInfo := objTaskDefinition.RegistrationInfo 
		objInfo.Author := A_UserName 
		objInfo.Description := DescriptionInfo
		objSettings := objTaskDefinition.Settings 
		objSettings.Enabled := True 
		objSettings.Hidden := False 
		objSettings.StartWhenAvailable := True 
		objSettings.ExecutionTimeLimit := "PT0S"
		objSettings.DisallowStartIfOnBatteries := False
		objSettings.StopIfGoingOnBatteries := False
		objFolder.RegisterTaskDefinition(taskName, objTaskDefinition, TaskCreateOrUpdate , "", "", TaskState ) 
		if IsAutorunEnabled(taskName)
			Return taskName
	}
}

SetBtnTxtColor(HWND, TxtColor) {
   Static HTML := {BLACK: "000000", GRAY: "808080", SILVER: "C0C0C0", WHITE: "FFFFFF", MAROON: "800000"
                , PURPLE: "800080", FUCHSIA: "FF00FF", RED: "FF0000", GREEN:  "008000", OLIVE:  "808000"
                , YELLOW: "FFFF00", LIME: "00FF00", NAVY: "000080", TEAL: "008080", AQUA: "00FFFF", BLUE: "0000FF"}
   Static BS_CHECKBOX := 0x2, BS_RADIOBUTTON := 0x4, BS_GROUPBOX := 0x7, BS_AUTORADIOBUTTON := 0x9
        , BS_LEFT := 0x100, BS_RIGHT := 0x200, BS_CENTER := 0x300, BS_TOP := 0x400, BS_BOTTOM := 0x800
        , BS_VCENTER := 0xC00, BS_BITMAP := 0x0080, SA_LEFT := 0x0, SA_CENTER := 0x1, SA_RIGHT := 0x2
        , WM_GETFONT := 0x31, BCM_SETIMAGELIST := 0x1602, IMAGE_BITMAP := 0x0, BITSPIXEL := 0xC
        , RCBUTTONS := BS_CHECKBOX | BS_RADIOBUTTON | BS_AUTORADIOBUTTON
        , BUTTON_IMAGELIST_ALIGN_LEFT := 0, BUTTON_IMAGELIST_ALIGN_RIGHT := 1, BUTTON_IMAGELIST_ALIGN_CENTER := 4
   ; -------------------------------------------------------------------------------------------------------------------
   ErrorLevel := ""
   GDIPDll := DllCall("Kernel32.dll\LoadLibrary", "Str", "Gdiplus.dll", "Ptr")
   VarSetCapacity(SI, 24, 0)
   Numput(1, SI)
   DllCall("Gdiplus.dll\GdiplusStartup", "PtrP", GDIPToken, "Ptr", &SI, "Ptr", 0)
   If (!GDIPToken) {
       ErrorLevel := "GDIPlus could not be started!`n`nSetBtnTxtColor won't work!"
       Return False
   }
   If !DllCall("User32.dll\IsWindow", "Ptr", HWND) {
      GoSub, CreateImageButton_GDIPShutdown
      ErrorLevel := "Invalid parameter HWND!"
      Return False
   }
   WinGetClass, BtnClass, ahk_id %HWND%
   ControlGet, BtnStyle, Style, , , ahk_id %HWND%
   If (BtnClass != "Button") || ((BtnStyle & 0xF ^ BS_GROUPBOX) = 0) || ((BtnStyle & RCBUTTONS) > 1) {
      GoSub, CreateImageButton_GDIPShutdown
      ErrorLevel := "You can use SetBtnTxtColor only for PushButtons!"
      Return False
   }
   PFONT := 0
   DC := DllCall("User32.dll\GetDC", "Ptr", HWND, "Ptr")
   BPP := DllCall("Gdi32.dll\GetDeviceCaps", "Ptr", DC, "Int", BITSPIXEL)
   HFONT := DllCall("User32.dll\SendMessage", "Ptr", HWND, "UInt", WM_GETFONT, "Ptr", 0, "Ptr", 0, "Ptr")
   DllCall("Gdi32.dll\SelectObject", "Ptr", DC, "Ptr", HFONT)
   DllCall("Gdiplus.dll\GdipCreateFontFromDC", "Ptr", DC, "PtrP", PFONT)
   DllCall("User32.dll\ReleaseDC", "Ptr", HWND, "Ptr", DC)
   If !(PFONT) {
      GoSub, CreateImageButton_GDIPShutdown
      ErrorLevel := "Couldn't get button's font!"
      Return False
   }
   VarSetCapacity(RECT, 16, 0)
   If !(DllCall("User32.dll\GetClientRect", "Ptr", HWND, "Ptr", &RECT)) {
      GoSub, CreateImageButton_GDIPShutdown
      ErrorLevel := "Couldn't get button's rectangle!"
      Return False
   }
   W := NumGet(RECT,  8, "Int"), H := NumGet(RECT, 12, "Int")
   BtnCaption := ""
   Len := DllCall("User32.dll\GetWindowTextLength", "Ptr", HWND) + 1
   If (Len > 1) {
      VarSetCapacity(BtnCaption, Len * (A_IsUnicode ? 2 : 1), 0)
      If !(DllCall("User32.dll\GetWindowText", "Ptr", HWND, "Str", BtnCaption, "Int", Len)) {
         GoSub, CreateImageButton_GDIPShutdown
         ErrorLevel := "Couldn't get button's caption!"
         Return False
      }
      VarSetCapacity(BtnCaption, -1)
   } Else {
      GoSub, CreateImageButton_GDIPShutdown
      ErrorLevel := "Couldn't get button's caption!"
      Return False
   }
   If HTML.HasKey(TxtColor)
      TxtColor := HTML[TxtColor]
   DllCall("Gdiplus.dll\GdipCreateBitmapFromScan0", "Int", W, "Int", H, "Int", 0
         , "UInt", 0x26200A, "Ptr", 0, "PtrP", PBITMAP)
   DllCall("Gdiplus.dll\GdipGetImageGraphicsContext", "Ptr", PBITMAP, "PtrP", PGRAPHICS)
   DllCall("Gdiplus.dll\GdipStringFormatGetGenericTypographic", "PtrP", PFORMAT)
   HALIGN := (BtnStyle & BS_CENTER) = BS_CENTER ? SA_CENTER : (BtnStyle & BS_CENTER) = BS_RIGHT ? SA_RIGHT
           : (BtnStyle & BS_CENTER) = BS_Left ? SA_LEFT : SA_CENTER
   DllCall("Gdiplus.dll\GdipSetStringFormatAlign", "Ptr", PFORMAT, "Int", HALIGN)
   VALIGN := (BtnStyle & BS_VCENTER) = BS_TOP ? 0 : (BtnStyle & BS_VCENTER) = BS_BOTTOM ? 2 : 1
   DllCall("Gdiplus.dll\GdipSetStringFormatLineAlign", "Ptr", PFORMAT, "Int", VALIGN)
   DllCall("Gdiplus.dll\GdipSetTextRenderingHint", "Ptr", PGRAPHICS, "Int", 3)
   NumPut(4, RECT, 0, "Float"), NumPut(2, RECT, 4, "Float")
   NumPut(W - 8, RECT, 8, "Float"), NumPut(H - 4, RECT, 12, "Float")
   DllCall("Gdiplus.dll\GdipCreateSolidFill", "UInt", "0xFF" . TxtColor, "PtrP", PBRUSH)
   DllCall("Gdiplus.dll\GdipDrawString", "Ptr", PGRAPHICS, "WStr", BtnCaption, "Int", -1, "Ptr", PFONT, "Ptr", &RECT
         , "Ptr", PFORMAT, "Ptr", PBRUSH)
   DllCall("Gdiplus.dll\GdipCreateHBITMAPFromBitmap", "Ptr", PBITMAP, "PtrP", HBITMAP, "UInt", 0X00FFFFFF)
   DllCall("Gdiplus.dll\GdipDisposeImage", "Ptr", PBITMAP)
   DllCall("Gdiplus.dll\GdipDeleteBrush", "Ptr", PBRUSH)
   DllCall("Gdiplus.dll\GdipDeleteStringFormat", "Ptr", PFORMAT)
   DllCall("Gdiplus.dll\GdipDeleteGraphics", "Ptr", PGRAPHICS)
   DllCall("Gdiplus.dll\GdipDeleteFont", "Ptr", PFONT)
   HIL := DllCall("Comctl32.dll\ImageList_Create", "UInt", W, "UInt", H, "UInt", BPP, "Int", 1, "Int", 0, "Ptr")
   DllCall("Comctl32.dll\ImageList_Add", "Ptr", HIL, "Ptr", HBITMAP, "Ptr", 0)
   VarSetCapacity(BIL, 20 + A_PtrSize, 0)
   NumPut(HIL, BIL, 0, "Ptr"), Numput(BUTTON_IMAGELIST_ALIGN_CENTER, BIL, A_PtrSize + 16, "UInt")
   GuiControl, , %HWND%
   SendMessage, BCM_SETIMAGELIST, 0, 0, , ahk_id %HWND%
   SendMessage, BCM_SETIMAGELIST, 0, &BIL, , ahk_id %HWND%
   GoSub, CreateImageButton_FreeBitmaps
   GoSub, CreateImageButton_GDIPShutdown
   Return True
   ; -------------------------------------------------------------------------------------------------------------------
   CreateImageButton_FreeBitmaps:
      DllCall("Gdi32.dll\DeleteObject", "Ptr", HBITMAP)
   Return    
   ; -------------------------------------------------------------------------------------------------------------------
   CreateImageButton_GDIPShutdown:
      DllCall("Gdiplus.dll\GdiplusShutdown", "Ptr", GDIPToken)
      DllCall("Kernel32.dll\FreeLibrary", "Ptr", GDIPDll)
   Return
}

SetButtonColor(ControlID, Color,HWND_:="ColorTheme", Margins:=1){
	GuiControlGet, hwnd, %HWND_%:Hwnd, %ControlID%
	VarSetCapacity(RECT, 16, 0), DllCall("User32.dll\GetClientRect", "Ptr", hwnd, "Ptr", &RECT)
	W := NumGet(RECT, 8, "Int") - (Margins * 1.5), H := NumGet(RECT, 12, "Int") - (Margins * 1.5)
	Color:=((Color&0xFF)<<16)+(Color&0xFF00)+((Color>>16)&0xFF)
	hbm:=CreateDIBSection(W, H), hdc := CreateCompatibleDC(), obm := SelectObject(hdc, hbm)
	hBrush:=DllCall("CreateSolidBrush", "UInt", Color, "UPtr"), obh:=SelectObject(hdc, hBrush)
	DllCall("Rectangle", "UPtr", hdc, "Int", 0, "Int", 0, "Int", W, "Int", H), SelectObject(hdc, obm)
	BUTTON_IMAGELIST_ALIGN_CENTER := 4, BS_BITMAP := 0x0080, BCM_SETIMAGELIST := 0x1602, BITSPIXEL := 0xC
	BPP := DllCall("Gdi32.dll\GetDeviceCaps", "Ptr", hdc, "Int", BITSPIXEL)
	HIL := DllCall("Comctl32.dll\ImageList_Create", "UInt", W, "UInt", H, "UInt", BPP, "Int", 6, "Int", 0, "Ptr")
	DllCall("Comctl32.dll\ImageList_Add", "Ptr", HIL, "Ptr", hbm, "Ptr", 0)
	; ; Create a BUTTON_IMAGELIST structure
	VarSetCapacity(BIL, 20 + A_PtrSize, 0), NumPut(HIL, BIL, 0, "Ptr")
	Numput(BUTTON_IMAGELIST_ALIGN_CENTER, BIL, A_PtrSize + 16, "UInt")
	SendMessage, BCM_SETIMAGELIST, 0, 0, , ahk_id %HWND%
	SendMessage, BCM_SETIMAGELIST, 0, &BIL, , ahk_id %HWND%
	SelectObject(hdc, obh), DeleteObject(hbm), DeleteObject(hBrush), DeleteDC(hdc)
}

CreateColoredBitmap(width, height, color) {
	hBitmap := CreateDIBSections(width, -height,, pBits)
	Loop % height {
		i := A_Index - 1
		Loop % width
			NumPut(color, pBits + width*4*i + (A_Index - 1)*4, "UInt")
	}
	Return hBitmap
}

CreateDIBSections(w, h, bpp := 32, ByRef ppvBits := 0)
{
	hdc := DllCall("GetDC", "Ptr", 0, "Ptr")
	VarSetCapacity(bi, 40, 0)
	NumPut( 40, bi,  0, "UInt")
	NumPut(  w, bi,  4, "UInt")
	NumPut(  h, bi,  8, "UInt")
	NumPut(  1, bi, 12, "UShort")
	NumPut(  0, bi, 16, "UInt")
	NumPut(bpp, bi, 14, "UShort")
	hbm := DllCall("CreateDIBSection", "Ptr", hdc, "Ptr", &bi, "UInt", 0, "PtrP", ppvBits, "Ptr", 0, "UInt", 0, "Ptr")
	DllCall("ReleaseDC", "Ptr", 0, "Ptr", hdc)
	return hbm
}

;-----------------------------------------配色----------------------------------------------------------
/*!
	函数: Dlg_Color(ByRef r_Color, hOwner:=0, Palette*)---->显示用于选择颜色的标准窗口对话框。

	参数:
		r_Color - 初始颜色-->默认设置为黑色.
		hOwner - 对话框对象的窗口ID, 如果有的话默认为0, i.e. 没有对象. 如果指定的DlgX和DlgY被忽略.
		Palette -最多16个RGB颜色值的数组。这些将成为对话框中的初始自定义颜色。
	Remarks:
		对话框中的自定义颜色在调用时被标记。如果用户选择OK，则将加载调色板阵列（如果存在）使用对话框中的自定义颜色。
	Returns:
		如果用户选择“确定”，返回True。否则返回False
*/
Dlg_Color(ByRef r_Color, hOwner:=0, Palette*){
	Static CHOOSECOLOR, A_CustomColors
	if !VarSetCapacity(A_CustomColors){
		If !objCount(Palette)
			Palette:= [0x1C7399,0xEEEEEC,0x014E8B,0x444444,0x009FE8,0xDEF9FA,0xF8B62D,0x90FC0F,0x0078D7,0x0D1B0A,0xB9D497,0x00ADEF,0x1778BF,0xFDF6E3,0x002B36,0xDEDEDE]
		VarSetCapacity(A_CustomColors,64,0)
		for Index, Value in Palette
			NumPut(Value, A_CustomColors, 4*(Index - 1), "UInt")
	}
	l_Color:=r_Color, l_Color:=((l_Color&0xFF)<<16)+(l_Color&0xFF00)+((l_Color>>16)&0xFF)
	;-- 创建并填充CHOOSECOLOR结构
	lStructSize:=VarSetCapacity(CHOOSECOLOR,(A_PtrSize=8) ? 72:36,0)
	NumPut(lStructSize,CHOOSECOLOR,0,"UInt")            ;-- lStructSize
	NumPut(hOwner,CHOOSECOLOR,(A_PtrSize=8) ? 8:4,"Ptr")
	;-- hwndOwner
	NumPut(l_Color,CHOOSECOLOR,(A_PtrSize=8) ? 24:12,"UInt")
	;-- RGB结果
	NumPut(&A_CustomColors,CHOOSECOLOR,(A_PtrSize=8) ? 32:16,"Ptr")
	;-- lpCustColors
	NumPut(0x00000103,CHOOSECOLOR,(A_PtrSize=8) ? 40:20,"UInt")
	;-- Flags
	RC:=DllCall("comdlg32\ChooseColor" . (A_IsUnicode ? "W":"A"),"Ptr",&CHOOSECOLOR)
	;-- 按下“取消”按钮或关闭对话框
	if (RC=0)
		Return False
	;-- 收集所选颜色
	l_Color:=NumGet(CHOOSECOLOR,(A_PtrSize=8) ? 24:12,"UInt")
	;-- 转换为RGB
	l_Color:=((l_Color&0xFF)<<16)+(l_Color&0xFF00)+((l_Color>>16)&0xFF)
	;-- 用选定的颜色更新
	r_Color:=Format("0x{:06X}",l_Color)

	Return True
}

;;==================================================================================================
;-----------------------------------------------------------
; IMEの状態をセット
;   SetSts          1:ON / 0:OFF
;   WinTitle="A"    対象Window
;   戻り値          0:成功 / 0以外:失敗
;-----------------------------------------------------------
;;DllCall("GetKeyboardLayout","UINT",DllCall("GetWindowThreadProcessId","UINT",WinActive("A"),"UINTP",0),UInt)
IME_SET(SetSts, WinTitle="A")    {
	ControlGet,hwnd,HWND,,,%WinTitle%
	if  (WinActive(WinTitle))   {
		ptrSize := !A_PtrSize ? 4 : A_PtrSize
		VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
		NumPut(cbSize, stGTI,  0, "UInt")  ;   DWORD   cbSize;
		hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
			? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
	}

	return DllCall("SendMessage"
		, UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
		, UInt, 0x0283 ;Message : WM_IME_CONTROL
		,  Int, 0x006  ;wParam  : IMC_SETOPENSTATUS
		,  Int, SetSts) ;lParam  : 0 or 1
}

;-------------------------------------------------------
; IME 入力モードセット
;   ConvMode        入力モード
;   WinTitle="A"    対象Window
;   戻り値          0:成功 / 0以外:失敗
;--------------------------------------------------------

IME_SetConvMode(ConvMode,WinTitle="A")   {
	ControlGet,hwnd,HWND,,,%WinTitle%
	if  (WinActive(WinTitle))   {
	ptrSize := !A_PtrSize ? 4 : A_PtrSize
	VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
	NumPut(cbSize, stGTI,  0, "UInt")  ;   DWORD   cbSize;
	hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
		? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
	}
	return DllCall("SendMessage"
		, UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
		, UInt, 0x0283     ;Message : WM_IME_CONTROL
		,  Int, 0x002      ;wParam  : IMC_SETCONVERSIONMODE
		,  Int, ConvMode)  ;lParam  : CONVERSIONMODE
}

IME_SetSentenceMode(SentenceMode,WinTitle="A")  {
	ControlGet,hwnd,HWND,,,%WinTitle%
	if  (WinActive(WinTitle))   {
		ptrSize := !A_PtrSize ? 4 : A_PtrSize
		VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
		NumPut(cbSize, stGTI,  0, "UInt")  ;   DWORD   cbSize;
		hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
			? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
	}
	return DllCall("SendMessage"
		, UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
		, UInt, 0x0283         ;Message : WM_IME_CONTROL
		,  Int, 0x004          ;wParam  : IMC_SETSENTENCEMODE
		,  Int, SentenceMode)  ;lParam  : SentenceMode
}

IME_GET(WinTitle="")
{
	;-----------------------------------------------------------
	; IMEの状態の取得
	;    対象： AHK v1.0.34以降
	;   WinTitle : 対象Window (省略時:アクティブウィンドウ)
	;   戻り値  1:ON 0:OFF
	;-----------------------------------------------------------
	ifEqual WinTitle,,  SetEnv,WinTitle,A
	WinGet,hWnd,ID,%WinTitle%
	DefaultIMEWnd := DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hWnd, Uint)
	;Message : WM_IME_CONTROL  wParam:IMC_GETOPENSTATUS
	DetectSave := A_DetectHiddenWindows
	DetectHiddenWindows,ON
	SendMessage 0x283, 0x005,0,,ahk_id %DefaultIMEWnd%
	DetectHiddenWindows,%DetectSave%
	Return ErrorLevel
}

/*
	F1::
		MsgBox % IME_CheckMode(ImmGetDefaultIMEWnd(WinActive()))
	Return
	WIN32下实现输入法所需要的一些必要消息、函数和说明
	IME消息
		以下列出IME中用到的消息。
		WM_IME_CHAR（IME得到了转换结果中的一个字符）
		WM_IME_COMPOSITION（IME根据用户击键的情况更改了按键组合状态）
		WM_IME_COMPOSITIONFULL（IME检测到按键组合窗口的区域无法继续扩展）
		WM_IME_CONTROL（由应用程序直接向IME发出控制请求）
		WM_IME_ENDCOMPOSITION（IME完成了对用户击键情况的组合）
		WM_IME_KEYDOWN（检测到“键盘上的某键被按下”的动作，同时在消息队列中保留该消息）
		WM_IME_KEYUP（检测到“键盘上的某键已弹起”的动作，同时在消息队列中保留该消息）
		WM_IME_NOTIFY（IME窗口发生了改变）
		WM_IME_REQUEST（通知：IME需要应用程序提供命令和请求信息）
		WM_IME_SELECT（操作系统将改变当前IME）
		WM_IME_SETCONTEXT（输入焦点转移到了某个窗口上）
		WM_IME_STARTCOMPOSITION（IME准备生成转换结果）

	IME函数
	　　本节列出了所有IME函数。
	函数
	 说明
	EnumInputContext
	 由应用程序定义的，提供给ImmEnumInputContext函数用来处理输入环境的一个回调函数。
	EnumRegisterWordProc
	 由应用程序定义的，结合ImmEnumRegisterWord函数一起使用的一个回调函数。
	ImmAssociateContext
	 建立指定输入环境与窗口之间的关联。
	ImmAssociateContextEx
	 更改指定输入环境与窗口（或其子窗口）之间的关联。
	ImmConfigureIME
	 显示指定的输入现场标识符的配置对话框。
	ImmCreateContext
	 创建一个新的输入环境，并为它分配内存和初始化它。
	ImmDestroyContext
	 销毁输入环境并释放和它关联的内存。
	ImmDisableIME
	 关闭一个线程或一个进程中所有线程的IME功能。
	ImmDisableTextFrameService
	 关闭指定线程的文本服务框架（TSF）功能－－虽然这里把它列了出来，但建议程序员最好不要使用这个函数。
	ImmEnumInputContext
	 获取指定线程的输入环境。
	ImmEnumRegisterWord
	 列举跟指定读入串、样式和注册串相匹配的注册串。
	ImmEscape
	 对那些不能通过IME API函数来访问的特殊输入法程序提供兼容性支持的一个函数。
	ImmGetCandidateList
	 获取一个候选列表。
	ImmGetCandidateListCount
	 获取候选列表的大小。
	ImmGetCandidateWindow
	 获取有关候选列表窗口的信息。
	ImmGetCompositionFont
	 获取有关当前用来显示按键组合窗口中的字符的逻辑字体的信息。
	ImmGetCompositionString
	 获取有关组合字符串的信息。
	ImmGetCompositionWindow
	 获取有关按键组合窗口的信息。
	ImmGetContext
	 获取与指定窗口相关联的输入环境。
	ImmGetConversionList
	 在不生成任何跟IME有关的消息的情况下，获取输入按键字符组合或输出文字的转换结果列表。
	ImmGetConversionStatus
	 获取当前转换状态。
	ImmGetDefaultIMEWnd
	 获取缺省IME类窗口的句柄。
	ImmGetDescription
	 复制IME的说明信息到指定的缓冲区中。
	ImmGetGuideLine
	 获取出错信息。
	ImmGetIMEFileName
	 获取跟指定输入现场相关联的IME文件名。
	ImmGetImeMenuItems
	 获取注册在指定输入环境的IME菜单上的菜单项。
	ImmGetOpenStatus
	 检测IME是否打开。
	ImmGetProperty
	 获取跟指定输入现场相关联的IME的属性和功能。
	ImmGetRegisterWordStyle
	 获取跟指定输入现场相关联的IME所支持的样式列表。
	ImmGetStatusWindowPos
	 获取状态窗口的位置。
	ImmGetVirtualKey
	 获取跟IME处理的键盘输入消息相关联的初始虚拟键值。
	ImmInstallIME
	 安装一个IME。
	ImmIsIME
	 检测指定的输入现场是否有和它相关的IME。
	ImmIsUIMessage
	 检查IME窗口消息并发送那些消息到特定的窗口。
	ImmNotifyIME
	 通知IME有关输入环境状态已改变的消息。
	ImmRegisterWord
	 注册一个输出文字到跟指定输入现场相关联的IME的字典中去。
	ImmReleaseContext
	 销毁输入环境并解除对跟它相关联的内存的锁定。
	ImmSetCandidateWindow
	 设置有关候选列表窗口的信息。
	ImmSetCompositionFont
	 设置用来显示按键组合窗口中的字符的逻辑字体。
	ImmSetCompositionString
	 设置按键组合字符串的字符内容、属性和子串信息。
	ImmSetCompositionWindow
	 设置按键组合窗口的位置。
	ImmSetConversionStatus
	 设置当前转换状态。
	ImmSetOpenStatus
	 打开或关闭IME功能。
	ImmSetStatusWindowPos
	 设置状态窗口的位置。
	ImmSimulateHotKey
	 在指定的窗口中模拟一个特定的IME热键动作，以触发该窗口相应的响应动作。
	ImmUnregisterWord
	 从跟指定输入环境相关联的IME的字典中注销一个输出文字。
	 
	IME命令
	　　以下列出IME中用到的命令（控制消息）。

	IMC_CLOSESTATUSWINDOW（隐藏状态窗口）
	IMC_GETCANDIDATEPOS（获取候选窗口的位置）
	IMC_GETCOMPOSITIONFONT（获取用来显示按键组合窗口中的文本的逻辑字体）
	IMC_GETCOMPOSITIONWINDOW（获取按键组合窗口的位置）
	IMC_GETSTATUSWINDOWPOS（获取状态窗口的位置）
	IMC_OPENSTATUSWINDOW（显示状态窗口）
	IMC_SETCANDIDATEPOS（设置候选窗口的位置）
	IMC_SETCOMPOSITIONFONT（设置用来显示按键组合窗口中的文本的逻辑字体）
	IMC_SETCOMPOSITIONWINDOW（设置按键组合窗口的样式）
	IMC_SETSTATUSWINDOWPOS（设置状态窗口的位置）
	IMN_CHANGECANDIDATE（IME通知应用程序：候选窗口中的内容将改变）
	IMN_CLOSECANDIDATE（IME通知应用程序：候选窗口将关闭）
	IMN_CLOSESTATUSWINDOW（IME通知应用程序：状态窗口将关闭）
	IMN_GUIDELINE（IME通知应用程序：将显示一条出错或其他信息）
	IMN_OPENCANDIDATE（IME通知应用程序：将打开候选窗口）
	IMN_OPENSTATUSWINDOW（IME通知应用程序：将创建状态窗口）
	IMN_SETCANDIDATEPOS（IME通知应用程序：已结束候选处理同时将移动候选窗口）
	IMN_SETCOMPOSITIONFONT（IME通知应用程序：输入内容的字体已更改）
	IMN_SETCOMPOSITIONWINDOW（IME通知应用程序：按键组合窗口的样式或位置已更改）
	IMN_SETCONVERSIONMODE（IME通知应用程序：输入内容的转换模式已更改）
	IMN_SETOPENSTATUS（IME通知应用程序：输入内容的状态已更改）
	IMN_SETSENTENCEMODE（IME通知应用程序：输入内容的语句模式已更改）
	IMN_SETSTATUSWINDOWPOS（IME通知应用程序：输入内容中的状态窗口的位置已更改）
	IMR_CANDIDATEWINDOW（通知：选定的IME需要应用程序提供有关候选窗口的信息）
	IMR_COMPOSITIONFONT（通知：选定的IME需要应用程序提供有关用在按键组合窗口中的字体的信息）
	IMR_COMPOSITIONWINDOW（通知：选定的IME需要应用程序提供有关按键组合窗口的信息）
	IMR_CONFIRMRECONVERTSTRING（通知：IME需要应用程序更改RECONVERTSTRING结构）
	IMR_DOCUMENTFEED（通知：选定的IME需要从应用程序那里取得已转换的字符串）
	IMR_QUERYCHARPOSITION（通知：选定的IME需要应用程序提供有关组合字符串中某个字符的位置信息）
	IMR_RECONVERTSTRING（通知：选定的IME需要应用程序提供一个用于自动更正的字符串）

	IME编程中需要用到的数据结构
	　　这里列了所有在使用输入法编辑器函数和消息时需要用到的数据结构。
	　　CANDIDATEFORM（描述候选窗口的位置信息）
	　　CANDIDATELIST（描述有关候选列表的信息）
	　　COMPOSITIONFORM（描述按键组合窗口的样式和位置信息）
	　　IMECHARPOSITION（描述按键组合窗口中的字符的位置信息）
	　　IMEMENUITEMINFO（描述IME菜单项的信息）
	　　RECONVERTSTRING（定义用于IME自动更正功能的字符串）
	　　REGISTERWORD（描述一个要注册的读入信息或文字内容）
	　　STYLEBUF（描述样式的标识符和名称）
*/
ImmGetDefaultIMEWnd(hWnd){
	return DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hWnd, Uint)
}

IME_CheckMode(hwnd){
	himc := DllCall("Imm32\ImmGetContext", "UInt", hwnd)
	ret := DllCall("Imm32\ImmGetOpenStatus", "UInt", himc)
	DllCall("Imm32\ImmReleaseContext", "UInt", hwnd, "UInt", himc)
	return ret
}

;;==================================================================================================
ChangeWindowIcon(IconFile, hWnd:="", IconNumber:=1, IconSize:=128) {    ;ico图标文件IconNumber和IconSize不用填，如果是icl图标库需要填
	hWnd :=hWnd?hWnd:WinExist("A")
	if (!hWnd)
		return "窗口不存在！"
	if not IconFile~="\.ico$"
		hIcon := LoadIcon(IconFile, IconNumber, IconSize)
	else
		hIcon := DllCall("LoadImage", uint, 0, str, IconFile, uint, 1, int, 0, int, 0, uint, LR_LOADFROMFILE:=0x10)
	if (!hIcon)
		return "图标文件不存在！"
	SendMessage, WM_SETICON:=0x80, ICON_SMALL2:=0, hIcon,, ahk_id %hWnd%  ; Set the window's small icon
	;;;SendMessage, STM_SETICON:=0x0170, hIcon, 0,, Ahk_ID %hWnd%
	SendMessage, WM_SETICON:=0x80, ICON_BIG:=1   , hIcon,, ahk_id %hWnd%  ; Set the window's big icon to the same one.
}


;获取exe/dll/icl文件中指定图标找返回
LoadIcon(Filename, IconNumber, IconSize)
{
	if DllCall("PrivateExtractIcons"
		, "str", Filename, "int", IconNumber-1, "int", IconSize, "int", IconSize
		, "ptr*", hIcon, "uint*", 0, "uint", 1, "uint", 0, "ptr")
		return hIcon
}

GetModuleFileNameEx( p_pid )
{
	if A_OSVersion in WIN_95,WIN_98,WIN_ME 
	{
		MsgBox, This Windows version (%A_OSVersion%) is not supported.
		return
	}
	; #define PROCESS_VM_READ           (0x0010)
	; #define PROCESS_QUERY_INFORMATION (0x0400)
	h_process := DllCall( "OpenProcess", "uint", 0x10|0x400, "int", false, "uint", p_pid )
	if ( ErrorLevel or h_process = 0 )
		return
	name_size = 255
	VarSetCapacity( name, name_size )
	result := DllCall( "psapi.dll\GetModuleFileNameEx" (A_IsUnicode ? "W":"A"), "uint", h_process, "uint", 0, "str", name, "uint", name_size )
	DllCall( "CloseHandle", "uint", h_process )

	return, name
}

EnumProcesses( byref r_pid_list )
{
	if A_OSVersion in WIN_95,WIN_98,WIN_ME
	{
		MsgBox, This Windows version (%A_OSVersion%) is not supported.
		return, false
	}

	pid_list_size := 4*1000
	VarSetCapacity( pid_list, pid_list_size )

	status := DllCall( "psapi.dll\EnumProcesses", "uint", &pid_list, "uint", pid_list_size, "uint*", pid_list_actual )
	if ( ErrorLevel or !status )
		return, false

	total := pid_list_actual//4

	r_pid_list=
	address := &pid_list
	loop, %total%
	{
		r_pid_list := r_pid_list "|" ( *( address )+( *( address+1 ) << 8 )+( *( address+2 ) << 16 )+( *( address+3 ) << 24 ) )
		address += 4
	}

	StringTrimLeft, r_pid_list, r_pid_list, 1

	return, total
}
;;==================================================================================================
Class MatchWeaselItems
{
	static list:=[]
	;;获取注册表安装路径信息
	GetWeaselPath(){
		RegRead, WeaselRoot, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, WeaselRoot
		RegRead, InstallDir, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, InstallDir
		RegRead, RimeUserDir, HKEY_CURRENT_USER\Software\Rime\Weasel, RimeUserDir
		RimeUserDir:=RimeUserDir?RimeUserDir:FileExist(A_AppData "\Rime\*.yaml")?A_AppData "\Rime":""

		Return {root:WeaselRoot,Install:InstallDir,user:RimeUserDir}
	}
	;;获取Default.yaml常用参数
	GetDefaultYaml(){
		this.List:=this.GetWeaselPath()
		if FileExist(this.List["user"] "\build\default.yaml"){
			Return Yaml(this.List["user"] "\build\default.yaml",1,"UTF-8")
		}
		Return {}
/*
		Static Mark:=""""
		this.List:=this.GetWeaselPath()
		if FileExist(this.List["user"] "\build\default.yaml"){
			this.DefaultContent:= this.GetFileContent(this.List["user"] "\build\Default.yaml")
			for key,value In [["page_size","page_size:\s"],["caption","\scaption:\s"],["hotkeys","`r`n    - [\w\""""]"],["schema_list","  - schema:\s"]]
			{
				Index:=1,this.List[value[1]]:=objCount(this.List[value[1]])?this.List[value[1]]:[]
				While Index:=RegExMatch(this.DefaultContent,"i)(?<=" value[2] ").+",item,Index+StrLen(item))
				{
					if item {
						this.List[value[1]].push(Trim(item,""""))
					}
				}
			}
			if FileExist(this.List["user"] "\" this.List["schema_list",1] ".custom.yaml"){
				if RegExMatch(this.GetFileContent(this.List["user"] "\" this.List["schema_list",1] ".custom.yaml"),"i)(?<=page_size\:\s)(\d+)|(?<=page_size" Mark "\:\s)(\d+)",match)
					this.List["page_size",1]:= RegExReplace(match,"[^\d]")
			}
			Return this.List
		}
		Return {}
*/
	}
	;;获取Weasel.yaml常用参数
	GetWeaselYaml(){
		this.List:=this.GetWeaselPath()
		if FileExist(this.List["user"] "\build\weasel.yaml"){
			Return Yaml(this.List["user"] "\build\weasel.yaml",1,"UTF-8")
		}
		Return {}
/*
		this.DefaultContent:= this.GetFileContent(this.List["user"] "\build\weasel.yaml")
		for key,value In [["app_options","i)([^\s\r\n]+)(:`r`n\s\s\s\sascii_mode:\s)(True|False)"],["color_scheme","i)(?<=\scolor_scheme:\s)(\w+)"],["preedit_type","i)(?<=\spreedit_type:\s)(\w+)"],["display_tray_icon","i)(?<=\sdisplay_tray_icon:\s)([^\s\r\n\t]+)"],["font_face","i)(?<=\sfont_face:\s)([^\s\r\n\t]+)"],["font_point","i)(?<=\sfont_point:\s)([^\s\r\n\t]+)"],["horizontal","i)(?<=\shorizontal:\s)([^\s\r\n\t]+)"],["inline_preedit","i)(?<=\sinline_preedit:\s)([^\s\r\n\t]+)"],["layout\border_width","i)(?<=\sborder_width:\s)([^\s\r\n\t]+)"],["layout\candidate_spacing","i)(?<=\scandidate_spacing:\s)([^\s\r\n\t]+)"],["layout\hilite_padding","i)(?<=\shilite_padding:\s)([^\s\r\n\t]+)"],["layout\hilite_spacing","i)(?<=\shilite_spacing:\s)([^\s\r\n\t]+)"],["layout\margin_x","i)(?<=\smargin_x:\s)([^\s\r\n\t]+)"],["layout\margin_y","i)(?<=\smargin_y:\s)([^\s\r\n\t]+)"],["layout\min_height","i)(?<=\smin_height:\s)([^\s\r\n\t]+)"],["layout\min_width","i)(?<=\smin_width:\s)([^\s\r\n\t]+)"],["layout\round_corner","i)(?<=\sround_corner:\s)([^\s\r\n\t]+)"],["layout\spacing","i)(?<=\sspacing:\s)([^\s\r\n\t]+)"],["layout\preedit_type","i)(?<=\spreedit_type:\s)([^\s\r\n\t]+)"]]
		{
			Index:=1,this.List[value[1]]:=objCount(this.List[value[1]])?this.List[value[1]]:[]
			While Index:=RegExMatch(this.DefaultContent,value[2],item,Index+StrLen(item1))
			{
				if (item1) {
					this.List[value[1]].push(item3?[Trim(item1,""""),Trim(item3,"""")]:Trim(item1,""""))
				}
			}
		}

		Return this.List
*/
	}
	;;获取用户资料同步目录
	GetInstallationYaml(){
		this.List:=this.GetWeaselPath()
		this.DefaultContent:= this.GetFileContent(FileExist(this.List["user"] "\Installation.yaml")?this.List["user"] "\Installation.yaml":this.List["root"] "\data\Installation.yaml")
		for key,value In [["installation_id","i)(?<=installation_id:\s)(.+)"],["sync_dir","i)(?<=sync_dir:\s)(.+)"]]
		{
			this.List[value[1]]:=objCount(this.List[value[1]])?this.List[value[1]]:[]
			if RegExMatch(this.DefaultContent,value[2],item)
				this.List[value[1]].push(RegExReplace(Trim(item,""""),"\\\\","\"))
		}
		this.List["sync_dir"]:= objCount(this.List["sync_dir"])?this.List["sync_dir"]:objCount(this.List["installation_id"])&&FileExist(this.List["user"] "\Installation.yaml")||objCount(this.List["installation_id"])&&FileExist(this.List["root"] "\data\Installation.yaml")?[this.List["user"]]:[]

		Return this.List
	}

	;;文件读取
	GetFileContent(FilePath,Encoding="UTF-8",Recycle:=0){  ;;Recycle=0时清理多余空行反之
		If FileExist(FilePath){
			FileEncoding,%Encoding%
			FileRead,chars,%FilePath%
			chars:=RegExReplace(RegExReplace(RegExReplace(chars,"`r`n","`r"),"`n","`r"),"`r","`r`n")
			if !Recycle {
				chars:=RegExReplace(RegExReplace(chars,"`r`n[\s\t]*`r`n","`r`n"),"(*BSR_ANYCRLF)\R+", "`r`n")
			}

			return Trim(chars)
		}
	}
	GetCustomSchemaConfig(SchemaId=""){
		Static SchemaPath
		this.List:=this.GetWeaselPath()
		SchemaPath:=SchemaId?this.List["user"] "\build\" SchemaId ".schema.yaml":this.List["user"] "\build\" this.GetDefaultYaml()["schema_list","",1,"schema"] ".schema.yaml"
		Return  Yaml(SchemaPath,1,"UTF-8")
/*
		if objCount(this.List:=this.GetDefaultYaml()){
			Return Yaml(this.List["user"] "\build\" this.List["schema_list",1] ".schema.yaml",1,"UTF-8")
		}
*/
		Return {}
	}
	;;修改Installation.Yaml
	ModifyInstallationYaml(obj){
		Static Mark,Flag
		Mark:="""",Flag:=0
		this.List:=this.GetWeaselPath()
		if !FileExist(this.List["user"] "\Installation.yaml")&&FileExist(this.List["root"] "\data\Installation.yaml")
			FileCopy,% this.List["root"] "\data\Installation.yaml",% this.List["user"] "\Installation.yaml"
		this.DefaultContent:=FileExist(this.List["user"] "\Installation.yaml")?this.GetFileContent(this.List["user"] "\Installation.yaml"):""
		if this.DefaultContent {
			for Section,element In obj
			{
				Switch Trim(Section)
				{
					case "sync_dir":
						if InStr(this.DefaultContent,"sync_dir:")
							this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(?<=sync_dir\:)[^\r\n]+",A_Space Mark RegExReplace(RTrim(element,"\"),"\\","\\") "\\" Mark),Flag++
						Else
							this.DefaultContent:=Trim(this.DefaultContent,"`r`n") ("`r`nsync_dir: " Mark RegExReplace(RTrim(element,"\"),"\\","\\") "\\" Mark),Flag++
					case "installation_id":
						if InStr(this.DefaultContent,"installation_id:")
							this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(?<=installation_id\:)[^\r\n]+",A_Space Mark Trim(element) Mark),Flag++
						Else
							this.DefaultContent:=Trim(this.DefaultContent,"`r`n") ("`r`ninstallation_id: " Mark Trim(element) Mark),Flag++

				}
			}
			if Flag {
				FileDelete,% this.List["user"] "\installation.yaml"
				FileAppend,% this.DefaultContent,% this.List["user"] "\installation.yaml",UTF-8
				
				Return Flag
			}
		}
	}
	;;修改Default.custom.yaml文件热键
	ModifyDefaultYaml(obj){
		Static Mark,Flag
		Mark:="""",Flag:=0
		this.List:=this.GetWeaselPath()
		this.DefaultContent:=FileExist(this.List["user"] "\default.custom.yaml")?this.GetFileContent(this.List["user"] "\default.custom.yaml"):"patch:`r`n"
		for Section,element In obj
		{
			Switch Section
			{
				case "switcher\caption":
					if this.DefaultContent~="i)switcher\/caption"{
						this.DefaultContent:= RegExReplace(this.DefaultContent,"i)(?<=switcher\/caption\:\s)[^\r\n]+|(?<=switcher\/caption" Mark "\:\s)[^\r\n]+",A_Space Mark Trim(element) Mark)
						Flag++
					}Else if this.DefaultContent~="i)\s+caption\:\s*"{
						this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(?<=\scaption\:)[^\r\n]*",A_Space Trim(element))
						Flag++
					}Else{
						this.DefaultContent:= RegExReplace(this.DefaultContent,"i)(patch\:\r\n)","$1  switcher:`r`n    caption: " Trim(element))
						Flag++
					}
				case "switcher\hotkeys":
					if InStr(this.DefaultContent,A_Space "hotkeys:"){
						this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(?<=hotkeys\:)(\s+\-\s+[\""""]*[a-zA-Z\+\_]+[\""""]*[^\r\n]*)+")
						this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(hotkeys\:)","$1`r`n" Trim(this.FormatItems(element,1),"`r`n") "`r`n")
						Flag++
					}Else{
						this.DefaultContent.= "`r`n  " Section ":`r`n" Trim(this.FormatItems(element,1),"`r`n"),flag++
					}
				case "schema_list":
					this.DefaultContent:= RegExReplace(this.DefaultContent,"m)\r\n\s*[\""""]*schema_list\:.*|\r\n\s*\-\s*\{schema:\s*.+")
					if !InStr(this.DefaultContent,"schema_list:"){
						this.DefaultContent.= "`r`n  schema_list:`r`n" Trim(this.FormatItems(element),"`r`n"),flag++
					}Else{
						this.DefaultContent:=RegExReplace(this.DefaultContent,"i)(?<=\sschema_list\:)\s*[^\r\n]*","`r`n" Trim(this.FormatItems(element),"`r`n")),flag++
					}
			}
		}
		if Flag {
			FileDelete,% this.List["user"] "\default.custom.yaml"
			FileAppend,% this.DefaultContent,% this.List["user"] "\default.custom.yaml",UTF-8
			
			Return Flag
		}
	}

	FormatItems(obj,Ishotkeys=0){
		Static st
		st:=""
		if !objCount(obj)&&obj
			Return A_Space obj
		for key,value In obj
		{
			st.=!Ishotkeys?"`r`n    - {schema: " value "}":"`r`n      - " value
		}

		Return st
	}

	;;修改Weasel.custom.yaml文件
	ModifyWeaselYaml(obj){
		Static Mark:=""""
		this.List:=this.GetWeaselPath()
		this.DefaultContent:=FileExist(this.List["user"] "\weasel.custom.yaml")?this.GetFileContent(this.List["user"] "\weasel.custom.yaml"):"patch:`r`n"
		for key,value In obj
		{
			Switch key
			{
				case "style/font_face":
					if objCount(value){
						StyleItem:=value[1]
					}Else{
						StyleItem:=value
					}
				Default:
					StyleItem:=value
			}
			RegExMatch(this.DefaultContent,"i).+[\/\s]+" RegExReplace(this.StringLower(key),".+\/") "[\""""]*\:.+",match)
			if match {
				this.DefaultContent:= RegExReplace(this.DefaultContent,"i)(?<=" this.StringLower(key) "[\""""]\:)[^\r\n]+|(?<=" this.StringLower(key) "\:)[^\r\n]+|(?<=[\s\/]" RegExReplace(this.StringLower(key),".+\/") "\:)[^\r\n]+|(?<=[\s\/]" RegExReplace(this.StringLower(key),".+\/") "[\""""]\:)[^\r\n]+",A_Space (StyleItem~="i)^\s*(\d|True|False)+\s*$"?StyleItem:Mark this.StringLower(StyleItem) Mark))
			}Else{
				this.DefaultContent:= RegExReplace(this.DefaultContent,"([\r\n]*patch\:\r\n)","$1  " Mark this.StringLower(key) Mark ": " (StyleItem~="i)^\s*(\d|True|False)+\s*$"?StyleItem:Mark this.StringLower(StyleItem) Mark) "`r`n")
			}
		}
		if (this.DefaultContent) {
			FileDelete,% this.List["user"] "\weasel.custom.yaml"
			FileAppend,% this.FormatYaml(this.DefaultContent),% this.List["user"] "\weasel.custom.yaml",UTF-8
			this.ModifyCustomYaml(obj,1)

			Return 1
		}
	}

	AppendColorThemes(ColorInfo){
		this.List:=this.GetWeaselPath()
		this.DefaultContent:=FileExist(this.List["user"] "\weasel.custom.yaml")?this.GetFileContent(this.List["user"] "\weasel.custom.yaml"):"patch:`r`n"
		this.DefaultContent:=MatchWeaselItems.FormatYaml(Trim(this.DefaultContent,"`r`n") . "`r`n`r`n" . Trim(ColorInfo,"`r`n"))
		FileDelete,% this.List["user"] "\weasel.custom.yaml"
		FileAppend,% this.DefaultContent,% this.List["user"] "\weasel.custom.yaml",UTF-8

		Return 1
	}

	;;进程状态修改
	ModifyWeaselAppOptions(obj){
		Static Item,Process_info
		Process_info:=""
		this.List:=this.GetWeaselPath()
		this.DefaultContent:=FileExist(this.List["user"] "\weasel.custom.yaml")?this.GetFileContent(this.List["user"] "\weasel.custom.yaml"):"patch:`r`n"
		for Section,element in obj
		{
			Item:=""
			for key,value in element
			{
				if value
					Item.=key ": " value ","
			}
			if Item:=Trim(Item,","){
				Process_info.="`r`n  app_options/" MatchWeaselItems.StringLower(Trim(Section)) ": {" Item "}"
			}
		}
		this.DefaultContent:= RegExReplace(this.DefaultContent,"m)\r\n\s*[\""""]*app_options.+|\r\n\s*ascii_mode:\s*.+")
		this.DefaultContent:= RegExReplace(this.DefaultContent,"([\r\n]*patch\:\r\n)","$1" Trim(Process_info,"`r`n") "`r`n")
		if (this.DefaultContent) {
			FileDelete,% this.List["user"] "\weasel.custom.yaml"
			FileAppend,% this.FormatYaml(this.DefaultContent),% this.List["user"] "\weasel.custom.yaml",UTF-8
			Return 1
		}
	}

	;;修改switches开关组
	ModifySwitcherState(obj){
		Static Mark,Flag,Index
		Mark:="""",Flag:=0,Index:=0
		for Section,element In obj`
		{
			for key,value In this.GetSchemaPath(this.GetDefaultYaml()["schema_list",""])
			{
				if Index:=this.GetSwitcherIndex(yaml(this.List["user"] "\build\" Trim(key) ".schema.yaml",1,"utf-8")["switches",""],Section){
					this.DefaultContent:=FileExist(value)?this.GetFileContent(value):"patch:`r`n"
					if InStr(this.DefaultContent,"switches/@" Index-1 "/reset"){
						this.DefaultContent:= RegExReplace(this.DefaultContent,"i)(?<=switches\/\@" Index-1 "\/reset[\""""]\:)[^\r\n]+|(?<=switches\/\@" Index-1 "\/reset\:)[^\r\n]+",A_Space element "  # " Section)
					}Else{
						this.DefaultContent:= Trim(this.DefaultContent,"`r`n") ("`r`n" A_Space A_Space Mark "switches/@" Index-1 "/reset" Mark ": " A_Space element "  # " A_Space Section "`r`n")
					}
					if (this.DefaultContent) {
						FileDelete,%value%
						FileAppend,% this.FormatYaml(this.DefaultContent),%value%,UTF-8
						Flag++
					}
				}
			}
		}

		Return Flag
	}

	GetSwitcherIndex(obj,item){
		for Section,element In obj
			if (element["name"]=item)
				Return Section

		Return 0
	}

	;;修改用户方案文件
	ModifyCustomYaml(obj,hide=0){
		Static Mark,Flag
		Mark:="""",Flag:=0
		for Section,element In this.GetSchemaPath(this.GetDefaultYaml()["schema_list",""])
		{
			this.DefaultContent:= element?this.GetFileContent(element):"patch:`r`n"
			for key,value In obj
			{
				Switch key
				{
					case "style/font_face":
						if (objCount(value)&&value[2]=RegExReplace(element,".+\\|\..+")){
							if InStr(this.DefaultContent,"font_face"){
								RegExMatch(this.DefaultContent,"i)[^\r\n]+font_face[^\r\n]+",match)
								if match {
									this.DefaultContent:=StrReplace(this.DefaultContent,match,RegExReplace(match,"^\s*[\#]+",A_Space))
									if (this.DefaultContent) {
										FileDelete,% this.List["user"] "\" Trim(Section) ".custom.yaml"
										FileAppend,% this.FormatYaml(this.DefaultContent),% element?element:this.List["user"] "\" Trim(Section) ".custom.yaml",UTF-8
										Flag++
									}
								}
							}
							Continue
						}Else if (objCount(value)&&value[2]<>RegExReplace(element,".+\\|\..+")){
							StyleItem:=value[1]
						}Else{
							StyleItem:=value
						}
					Default:
						StyleItem:=value
				}

				RegExMatch(this.DefaultContent,"i).+[^a-zA-Z0-9\#]+" RegExReplace(this.StringLower(key),".+\/") "[\""""]*\:.+",match)
				if match {
					this.DefaultContent:= StrReplace(this.DefaultContent, match,(hide?"  # ":"  ") Mark this.StringLower(key) Mark ": " (StyleItem~="i)^\s*(\d|True|False)+\s*$"?StyleItem:Mark this.StringLower(StyleItem) Mark))
				}Else{
					this.DefaultContent:= RegExReplace(this.DefaultContent,"([\r\n]*patch\:\r\n)","$1  " (Hide?"# ":"") Mark this.StringLower(key) Mark ": " (StyleItem~="i)^\s*(\d|True|False)+\s*$"?StyleItem:Mark this.StringLower(StyleItem) Mark) "`r`n")
				}
			}
			if (this.DefaultContent) {
				FileDelete,% this.List["user"] "\" Trim(Section) ".custom.yaml"
				FileAppend,% this.FormatYaml(this.DefaultContent),% element?element:this.List["user"] "\" Trim(Section) ".custom.yaml",UTF-8
				Flag++
			}
		}

		Return Flag
	}
	;;获取方案文件路径
	GetSchemaPath(obj){
		Static schemalist
		schemalist:={}
		this.List:=this.GetWeaselPath()
		for Section,element In obj
			schemalist[Trim(element["schema"])]:=FileExist(this.List["user"] "\" Trim(element["schema"]) ".custom.yaml")?this.List["user"] "\" Trim(element["schema"]) ".custom.yaml":""

		Return schemalist
	}
	;;同步用户资料
	SyncWeasel(){
		this.List:=this.GetWeaselPath()
		Static WeaselRoot,RimeUserDir
		WeaselRoot:=this.List["root"], RimeUserDir:=this.List["user"]
		if FileExist(WeaselRoot "\WeaselDeployer.exe"){
			Command = "%WeaselRoot%\WeaselDeployer.exe" /sync
			Run *RunAs cmd.exe /c %Command%, , Hide
			sleep 8000
			For key,value In ["~","`%","`$","rime","``"]
				FileDelete,%A_Temp%\%value%*.*
		}Else
			TrayTip,Error,未发现小狼毫安装路径！,,3
	}
	;;小狼毫重新部署
	DeployWeasel(){
		this.List:=this.GetWeaselPath()
		Static WeaselRoot,RimeUserDir
		WeaselRoot:=this.List["root"], RimeUserDir:=this.List["user"]
		if FileExist(WeaselRoot "\WeaselDeployer.exe"){
			FileDelete,%RimeUserDir%\build\*.schema.yaml
			FileDelete,%RimeUserDir%\build\default.yaml
			FileDelete,%RimeUserDir%\build\weasel.yaml
			For key,value In ["~","`%","`$","rime","``"]
				FileDelete,%A_Temp%\%value%*.*
			Command = "%WeaselRoot%\WeaselDeployer.exe" /deploy
			Run *RunAs cmd.exe /c %Command%, , Hide
		}Else
			TrayTip,Error,未发现小狼毫安装路径！,,3
	}
	;;算法服务启动/结束
	ToggleRunWeasel(){
		this.List:=this.GetWeaselPath()
		Static WeaselRoot,RimeUserDir
		WeaselRoot:=this.List["root"], RimeUserDir:=this.List["user"]

		Process, Exist , WeaselServer.exe
		If ErrorLevel {
			TrayTip,小狼毫助手,算法服务已终止，请在托盘菜单启用！,,3
			Process, Close , WeaselServer.exe
			For key,value In ["~","`%","`$","rime","``","mpr"]
				FileDelete,%A_Temp%\%value%*.*
		}else{
			For key,value In ["~","`%","`$","rime","``","mpr"]
				FileDelete,%A_Temp%\%value%*.*
			if FileExist(WeaselRoot "\WeaselServer.exe"){
				TrayTip,小狼毫助手,算法服务已运行！,,1
				Run *RunAs "%WeaselRoot%\WeaselServer.exe" /restart
			}else{
				TrayTip,Error,未发现小狼毫安装路径！,,3
			}
		}

	}

	;;格式化yaml文件缩进
	FormatYaml(fileContent){
		Loop,Parse,fileContent,`n,`r
		{
			if A_LoopField~="^\s+(\""""|translator|switches|menu|history|style|key_binder|app_options|preset_color_schemes).+"
				fileContent:=RegExReplace(fileContent,A_LoopField,"  " RegExReplace(A_LoopField,"^\s+"))
		}

		Return fileContent
	}

	StringLower(ByRef InputVar, T = "")
	{
		StringLower, InputVar, InputVar, %T%
		return InputVar
	}

	StringUpper(ByRef InputVar, T = "")
	{
		StringUpper, InputVar, InputVar, %T%
		return InputVar
	}
}

;;=========================================================================================================

/*
	Class Dock
		Attach a window to another
	Author
		Soft (visionary1 예지력)
	version
		0.1 (2017.04.20)
		0.2 (2017.05.06)
		0.2.1 (2017.05.07)
		0.2.1.1 bug fixed (2017.05.09)
		0.2.2 testing multiple docks... (2017.05.09)
	License
		WTFPL (http://wtfpl.net/)
	Dev env
		Windows 10 pro x64
		AutoHotKey H v1.1.25.01 32bit
	To Do...
		Multiple Dock, group windows...
	thanks to
		Helgef for overall coding advices
*/
class Dock
{
	static EVENT_OBJECT_LOCATIONCHANGE := 0x800B
	, EVENT_OBJECT_FOCUS := 0x8005, EVENT_OBJECT_DESTROY := 0x8001
	, EVENT_MIN := 0x00000001, EVENT_MAX := 0x7FFFFFFF ;for debug
	, EVENT_SYSTEM_FOREGROUND := 0x0003

	/*
		Instance := new Dock(Host hwnd, Client hwnd, [Callback], [CloseCallback])
			Host hwnd
				hwnd of a Host window
			Client hwnd
				hwnd of a window that follows Host window (window that'll be attached to a Host window)
			[Callback]
				a func object, or a bound func object
				if omitted, default EventsHandler will be used, which is hard-coded in 'Dock.EventsHandler'
				To construct your own events handler, I advise you to see Dock.EventsHandler first
			[CloseCallback]
				a func object, or a bound func object
				called when Host window is destroyed, see 'Dock Example.ahk' for practical usuage
	*/
	__New(Host, Client, Callback := "", CloseCallback := "")
	{
		this.hwnd := []
		this.hwnd.Host := Host
		this.hwnd.Client := Client
		WinSet, ExStyle, +0x80, % "ahk_id " this.hwnd.Client

		this.Bound := []

		this.Callback := IsObject(Callback) ? Callback : ObjBindMethod(Dock.EventsHandler, "Calls")
		this.CloseCallback := IsFunc(CloseCallback) || IsObject(CloseCallback) ? CloseCallback

		/*
			lpfnWinEventProc
		*/
		this.hookProcAdr := RegisterCallback("_DockHookProcAdr",,, &this)

		/*
			idProcess
		*/
		;WinGet, idProcess, PID, % "ahk_id " . this.hwnd.Host
		idProcess := 0

		/*
			idThread
		*/
		;idThread := DllCall("GetWindowThreadProcessId", "Ptr", this.hwnd.Host, "Int", 0)
		idThread := 0

		DllCall("CoInitialize", "Int", 0)

		this.Hook := DllCall("SetWinEventHook"
				, "UInt", Dock.EVENT_SYSTEM_FOREGROUND 		;eventMin
				, "UInt", Dock.EVENT_OBJECT_LOCATIONCHANGE 	;eventMax
				, "Ptr", 0				  	;hmodWinEventProc
				, "Ptr", this.hookProcAdr 			;lpfnWinEventProc
				, "UInt", idProcess			 	;idProcess
				, "UInt", idThread			  	;idThread
				, "UInt", 0)					;dwFlags
	}

	/*
		Instance.Unhook()
			unhooks Dock and frees memory
	*/
	Unhook()
	{
		DllCall("UnhookWinEvent", "Ptr", this.Hook)
		DllCall("CoUninitialize")
		DllCall("GlobalFree", "Ptr", this.hookProcAdr)
		this.Hook := ""
		this.hookProcAdr := ""
		this.Callback := ""
		WinSet, ExStyle, -0x80, % "ahk_id " this.hwnd.Client
	}

	__Delete()
	{
		this.Delete("Bound")

		If (this.Hook)
			this.Unhook()

		this.CloseCallback := ""
	}

	/*
		provisional
	*/
	Add(hwnd, pos := "")
	{
		static last_hwnd := 0

		this.Bound.Push( new this( !NumGet(&this.Bound, 4*A_PtrSize) ? this.hwnd.Client : last_hwnd, hwnd ) )

		If pos Contains Top,Bottom,R,Right,L,Left
			this.Bound[NumGet(&this.Bound, 4*A_PtrSize)].Position(pos)

		last_hwnd := hwnd
	}

	/*
		Instance.Position(pos)
			pos - sets position to dock client window
				Top - sets to Top side of the host window
				Bottom - sets to bottom side of the host window
				R or Right - right side
				L or Left -  left side
	*/
	Position(pos)
	{
		this.pos := pos
		Return this.EventsHandler.EVENT_OBJECT_LOCATIONCHANGE(this, "host")
	}

	/*
		Default EventsHandler
	*/
	class EventsHandler extends Dock.HelperFunc
	{
		Calls(self, hWinEventHook, event, hwnd)
		{
			Critical

			if (!WinExist("ahk_id " self.hwnd.Client)&&WinActive("ahk_id " self.hwnd.Host)){
				self.hwnd.Client:=ShowPreviewGui()
				WinActivate,% "ahk_id " self.hwnd.Host
			}

			If (hwnd = self.hwnd.Host)    ;;主窗口
			{
				Return this.Host(self, event)
			}

			If (hwnd = self.hwnd.Client)    ;;副窗口
			{
				Return this.Client(self, event)
			}
		}

		Host(self, event)
		{
			If (event = Dock.EVENT_SYSTEM_FOREGROUND)
			{
				Return this.EVENT_SYSTEM_FOREGROUND(self.hwnd.Client)
			}

			If (event = Dock.EVENT_OBJECT_LOCATIONCHANGE)
			{
				Return this.EVENT_OBJECT_LOCATIONCHANGE(self, "host")
			}

			If (event = Dock.EVENT_OBJECT_DESTROY)
			{
				self.Unhook()
				If (IsFunc(self.CloseCallback) || IsObject(self.CloseCallback))
					Return self.CloseCallback()
			}
		}

		Client(self, event)
		{
			If (event = Dock.EVENT_SYSTEM_FOREGROUND)
			{
				Return this.EVENT_SYSTEM_FOREGROUND(self.hwnd.Host)
			}

			If (event = Dock.EVENT_OBJECT_LOCATIONCHANGE)
			{
				Return this.EVENT_OBJECT_LOCATIONCHANGE(self, "client")
			}
		}

		/*
			Called when host window got focus
			without this, client window can't be showed (can't set to top)
		*/
		EVENT_SYSTEM_FOREGROUND(hwnd)
		{
			Return this.WinSetTop(hwnd)
		}

		/*
			Called when host window is moved
		*/
		EVENT_OBJECT_LOCATIONCHANGE(self, via)
		{
			Host := this.WinGetPos(self.hwnd.Host)
			Client := this.WinGetPos(self.hwnd.Client)

			If InStr(self.pos, "Top")
			{
				If (via = "host")
				{
					Return this.MoveWindow(self.hwnd.Client 	;hwnd
								, Host.x		;x
								, Host.y - Client.h 	;y
								, Client.w	  	;width
								, Client.h) 		;height
				}

				If (via = "client")
				{
					Return this.MoveWindow(self.hwnd.Host	   	;hwnd
								, Client.x	  	;x
								, Client.y + Client.h   ;y
								, Host.w		;width
								, Host.h)	   	;height
				}
			}

			If InStr(self.pos, "Bottom")
			{
				If (via = "host")
				{		   
					Return this.MoveWindow(self.hwnd.Client	 	;hwnd
								, Host.x		;x
								, Host.y + Host.h   	;y
								, Client.w	  	;width
								, Client.h)	 	;height
				}

				If (via = "client")
				{
					Return this.MoveWindow(self.hwnd.Host	   	;hwnd
								, Client.x	  	;x
								, Client.y - Host.h 	;y
								, Host.w		;width
								, Host.h)	   	;height
				}
			}

			If InStr(self.pos, "R")
			{
				If (via = "host")
				{
					Return this.MoveWindow(self.hwnd.Client	 	;hwnd
								, Host.x + Host.w   	;x
								, Host.y		;y
								, Client.w	  	;width
								, Client.h)	 	;height	
				}

				If (via = "client")
				{
					Return this.MoveWindow(self.hwnd.Host	   	;hwnd
								, Client.x - Host.w 	;x
								, Client.y	  	;y
								, Host.w		;width
								, Host.h)	   	;height
				}
			}

			If InStr(self.pos, "L")
			{
				If (via = "host")
				{
					Return this.MoveWindow(self.hwnd.Client	 	;hwnd
								, Host.x - Client.w 	;x
								, Host.y		;y
								, Client.w	  	;width
								, Client.h)	 	;height	
				}

				If (via = "client")
				{
					Return this.MoveWindow(self.hwnd.Host	   	;hwnd
								, Client.x + Client.w   ;x
								, Client.y	  	;y
								, Host.w		;width
								, Host.h)	   	;height	
				}
			}
		}
	}

	class HelperFunc
	{
		WinGetPos(hwnd)
		{
			WinGetPos, hX, hY, hW, hH, % "ahk_id " . hwnd
			Return {x: hX, y: hY, w: hW, h: hH}
		}

		WinSetTop(hwnd)
		{
			WinSet, AlwaysOnTop, On, % "ahk_id " . hwnd
			WinSet, AlwaysOnTop, Off, % "ahk_id " . hwnd
		}

		MoveWindow(hwnd, x, y, w, h)
		{
			Return DllCall("MoveWindow", "Ptr", hwnd, "Int", x, "Int", y, "Int", w, "Int", h, "Int", 1)
		}

		Run(Target)
		{
			Try Run, % Target,,, OutputVarPID
			Catch, 
				Throw, "Couldn't run " Target

			WinWait, % "ahk_pid " OutputVarPID

			Return WinExist("ahk_pid " OutputVarPID)
		}
	}
}

_DockHookProcAdr(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime)
{
	this := Object(A_EventInfo)
	this.Callback.Call(this, hWinEventHook, event, hwnd)
}

CloseCallback(self)
{
	WinKill, % "ahk_id " self.hwnd.Client
}

;;=====================================================================================================
; ==================================================================================================================================
; Sets the colors for selected rows in a ListView.
; Parameters:
;     HLV      -  handle (HWND) of the ListView control.
;     BkgClr   -  background color as RGB integer value (0xRRGGBB).
;                 If omitted or empty the ListViews's background color will be used.
;     TxtClr   -  text color as RGB integer value (0xRRGGBB).
;                 If omitted or empty the ListView's text color will be used.
;                 If both BkgColor and TxtColor are omitted or empty the control will be reset to use the default colors.
;     Dummy    -  must be omitted or empty!!!
; Return value:
;     No return value.
; Remarks:
;     The function adds a handler for WM_NOTIFY messages to the chain of existing handlers.
; ==================================================================================================================================
LV_SetSelColors(HLV, BkgClr := "", TxtClr := "", Dummy := "") {
	Static OffCode := A_PtrSize * 2              ; offset of code        (NMHDR)
		  , OffStage := A_PtrSize * 3             ; offset of dwDrawStage (NMCUSTOMDRAW)
		  , OffItem := (A_PtrSize * 5) + 16       ; offset of dwItemSpec  (NMCUSTOMDRAW)
		  , OffItemState := OffItem + A_PtrSize   ; offset of uItemState  (NMCUSTOMDRAW)
		  , OffClrText := (A_PtrSize * 8) + 16    ; offset of clrText     (NMLVCUSTOMDRAW)
		  , OffClrTextBk := OffClrText + 4        ; offset of clrTextBk   (NMLVCUSTOMDRAW)
		  , Controls := {}
		  , MsgFunc := Func("LV_SetSelColors")
		  , IsActive := False
	Local Item, H, LV, Stage
	If (Dummy = "") { ; user call ------------------------------------------------------------------------------------------------------
		If (BkgClr = "") && (TxtClr = "")
			Controls.Delete(HLV)
		Else {
			If (BkgClr <> "")
				Controls[HLV, "B"] := ((BkgClr & 0xFF0000) >> 16) | (BkgClr & 0x00FF00) | ((BkgClr & 0x0000FF) << 16) ; RGB -> BGR
			If (TxtClr <> "")
				Controls[HLV, "T"] := ((TxtClr & 0xFF0000) >> 16) | (TxtClr & 0x00FF00) | ((TxtClr & 0x0000FF) << 16) ; RGB -> BGR
		}
		If (Controls.MaxIndex() = "") {
			If (IsActive) {
				OnMessage(0x004E, MsgFunc, 0)
				IsActive := False
		}  }
		Else If !(IsActive) {
			OnMessage(0x004E, MsgFunc)
			IsActive := True
	}  }
	Else { ; system call ------------------------------------------------------------------------------------------------------------
		; HLV : wParam, BkgClr : lParam, TxtClr : uMsg, Dummy : hWnd
		H := NumGet(BkgClr + 0, "UPtr")
		If (LV := Controls[H]) && (NumGet(BkgClr + OffCode, "Int") = -12) { ; NM_CUSTOMDRAW
			Stage := NumGet(BkgClr + OffStage, "UInt")
			If (Stage = 0x00010001) { ; CDDS_ITEMPREPAINT
				Item := NumGet(BkgClr + OffItem, "UPtr")
				If DllCall("SendMessage", "Ptr", H, "UInt", 0x102C, "Ptr", Item, "Ptr", 0x0002, "UInt") { ; LVM_GETITEMSTATE, LVIS_SELECTED
					; The trick: remove the CDIS_SELECTED (0x0001) and CDIS_FOCUS (0x0010) states from uItemState and set the colors.
					NumPut(NumGet(BkgClr + OffItemState, "UInt") & ~0x0011, BkgClr + OffItemState, "UInt")
					If (LV.B <> "")
						NumPut(LV.B, BkgClr + OffClrTextBk, "UInt")
					If (LV.T <> "")
						NumPut(LV.T, BkgClr + OffClrText, "UInt")
					Return 0x02 ; CDRF_NEWFONT
			}  }
			Else If (Stage = 0x00000001) ; CDDS_PREPAINT
				Return 0x20 ; CDRF_NOTIFYITEMDRAW
			Return 0x00 ; CDRF_DODEFAULT
}}}